AngularJS: ng-switch-when with an OR

后端 未结 5 2066
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 15:34

Is it possible to have an OR in ng-switch-when?

5条回答
  •  渐次进展
    2020-12-15 16:20

    I created a simple directive in place of ngSwitchWhen that allows you to specify multiple cases for a single tag. It also allows you to specify dynamic values instead of purely static values.

    One caveat, it only evaluates the expression once upon compile time, so you must return the correct value immediately. For my purposes this was fine as I was wanting to use constants defined elsewhere in the application. It could probably be modified to dynamically re-evaluate the expressions but that would require more testing with ngSwitch.

    I am use angular 1.3.15 but I ran a quick test with angular 1.4.7 and it worked fine there as well.

    Plunker Demo

    The Code

    module.directive('jjSwitchWhen', function() {
        // Exact same definition as ngSwitchWhen except for the link fn
        return {
            // Same as ngSwitchWhen
            priority: 1200,
            transclude: 'element',
            require: '^ngSwitch',
            link: function(scope, element, attrs, ctrl, $transclude) {
                var caseStms = scope.$eval(attrs.jjSwitchWhen);
                caseStms = angular.isArray(caseStms) ? caseStms : [caseStms];
    
                angular.forEach(caseStms, function(caseStm) {
                    caseStm = '!' + caseStm;
                    ctrl.cases[caseStm] = ctrl.cases[caseStm] || [];
                    ctrl.cases[caseStm].push({ transclude: $transclude, element: element });
                });
            }
        };
    });
    

    Usage

    Controller
      $scope.types = {
          audio: '.mp3', 
          video: ['.mp4', '.gif'],
          image: ['.jpg', '.png', '.gif'] // Can have multiple matching cases (.gif)
      };
    
    Template
      
    Audio
    Video
    Image
    Document
    Invalid Type

提交回复
热议问题