为什么指令不设类?

时间:2017-02-22 20:12:57

标签: angularjs

我尝试编写自定义指令Angular JS,它根据传入的参数将类设置为元素:

angular.module('hello', [])
    .directive("testCase", function(){

   return {
        restrict: 'A',
        scope: {
            'condition': '='
        },
        link: function (scope, element, attrs) {
           switch (scope.condition) {
              case "pending":
                element.css('color', 'yellow');
                break;
              case 'active':
                element.css('color', 'green');
                break;
              case "archived":
              case "finished":
              case "completed":
                element.css('color', 'gray');
                break;
                }

        }
        }
});

http://jsfiddle.net/9h29R/71/

但是当我传递param" active"

时,目录不会设置类

2 个答案:

答案 0 :(得分:1)

你只是缺少引号。您需要传递字符串,否则angular会将active编译为父范围变量。检查工作小提琴:http://jsfiddle.net/9h29R/73/

<div ng-app="hello">
    <div test-case condition="'active'">Active</div>    
</div>

答案 1 :(得分:1)

@Slava。 K确认错误。只是为了好玩,以下是使用17/11/2016 09:00设置样式和元素上任何其他属性的另一种方法:

JS

attrs.$set

标记

angular.module('hello', [])
  .directive("testCase", function() {

    return {
      restrict: 'A',
      scope: {
        'condition': '='
      },
      link: function(scope, element, attrs) {

        var setStyle = function() {

          switch (attrs.condition) {

            case "pending":
              return "color: yellow"
            case "active":
              return "color: green"
            case "archived":
            case "finished":
            case "completed":
              return "color: gray"
          }
        };

        attrs.$set('style', setStyle());
      }

    }
  });

The Fiddler

http://jsfiddle.net/zh9u45nn/2/