如何根据ng-class设置的类应用AngularJS指令?

car*_*nts 43 angularjs angularjs-directive

我试图有条件地将指令应用于基于其类的元素.

这是我的问题的一个简单案例,请看这个小提琴的结果.对于这个例子,我使用类名映射到booleans形式的ng-classwith true; 在我的实际情况中,我想使用函数的布尔结果.

标记:

<div ng-app="example">
  <div class="testcase">
    This will have the directive applied as I expect
  </div>
  <div ng-class="{'testcase':true}">
    This will not have the directive applied but I expect it to
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

JS:

angular.module('example', [])
  .directive('testcase', function() {
      return {
          restrict: 'C',
          link: function(scope, element, attrs) {
              element.css('color', 'red');
          }
      }
    }
  );
Run Code Online (Sandbox Code Playgroud)

为什么指令不适用于div通过它的类ng-class?我是否误解了AngularJS处理指令的顺序?

我应该如何基于对表达式的求值有条件地将指令应用于元素?

Jai*_*ejo 24

ng-class在编译过程之后,只需在DOM上设置类.

也许应用指令的更好方法是通过HTML属性:

<div test-case>
Run Code Online (Sandbox Code Playgroud)

当然,这不是有条件的,但我会将条件留给指令:

<div ng-app="example" ng-controller="exampleCtrl">
    <div test-case condition="dynamicCondition">Hello</div>
    <input type="checkbox" ng-model="dynamicCondition"/> Condition 
</div>
Run Code Online (Sandbox Code Playgroud)

angular.module('example', [])
    .controller('exampleCtrl', function ($scope) {
        $scope.dynamicCondition = false;
    })
    .directive('testCase', function () {
    return {
        restrict: 'A',
        scope: {
            'condition': '='
        },
        link: function (scope, element, attrs) {
            scope.$watch('condition', function(condition){
                if(condition){
                    element.css('color', 'red');
                }
                else{
                    element.css('color', 'black');
                };
            });
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

请注意,指令名称testCase不是testcase,该scope: {'condition': '='},位确保条件属性已同步并可用,scope.condition并且watch每次第一个表达式更改值时都会计算第二个参数.JsFiddle 在这里.

也许你也应该研究一下ng-switch:

<div ng-switch="conditionFunction()">
  <div ng-when="true" test-case>Contents when conditionFunction() returns true</div>
  <div ng-when="false">Contents when conditionFunction() returns false</div>
</div>
Run Code Online (Sandbox Code Playgroud)