43

我正在尝试根据其类有条件地将指令应用于元素。

这是我的问题的一个简单案例,请参阅此 fiddle 中的结果。对于这个例子,我使用类名映射到布尔形式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>

JS:

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

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

我应该如何根据表达式的评估有条件地将指令应用于元素?

4

3 回答 3

24

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

应用该指令的更好方法可能是通过 HTML 属性:

<div test-case>

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

<div ng-app="example" ng-controller="exampleCtrl">
    <div test-case condition="dynamicCondition">Hello</div>
    <input type="checkbox" ng-model="dynamicCondition"/> Condition 
</div>

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');
                };
            });
        }
    }
});

请注意指令名称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>
于 2013-09-03T18:56:12.323 回答
1
angular.module('example', [])
  .directive('testCase', function() {
      return {
          restrict: 'C',
          link: function(scope, element, attrs) {
            element.css('color', 'red');
          }
      }
    })
于 2016-08-16T09:20:01.163 回答
0

据我说,不要像这个问题一样使用基于 ng-class 设置的类的条件指令。

不要使用这个

<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>

因为在复杂的情况下处理真的很复杂,所以总是在你的自定义指令中使用条件。

用这个

link: function (scope, element, attrs) {
    scope.$watch('condition', function(condition){
        if(condition){
            // something going here
        }
        else{
            // something going here
        };
    });
}
于 2017-09-06T07:42:21.020 回答