Angular.js ng-switch-when not working with dynamic data?

前端 未结 2 1152
忘掉有多难
忘掉有多难 2020-12-05 02:54

I\'m trying to get Angular to generate a CSS slider based on my data. I know that the data is there and am able to generate it for the buttons, but the code won\'t populate

2条回答
  •  旧时难觅i
    2020-12-05 03:12

    Jon is definitely right on. Angular does not support dynamic ngSwitchWhen values. But I wanted it to. I found it actually exceptionally simple to use my own directive in place of ngSwitchWhen. Not only does it support dynamic values but it supports multiple values for each statement (similar to JS switch fall-throughs).

    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

提交回复
热议问题