前端之家收集整理的这篇文章主要介绍了
如何应用基于ng-class设置的类的AngularJS指令?,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_
301_0@
我试图有条件地应用指令基于其类的元素。
这里是我的问题的一个简单的例子,see the results in this fiddle.对于这个例子,我使用类名的布局的ng-class的布尔形式与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');
}
}
}
);
为什么指令不应用于通过ng-class获得类的div?我是否误解了AngularJS处理指令的顺序?
我应该如何有条件地根据表达式的求值将一个指令应用到一个元素?
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,attrs) {
scope.$watch('condition',function(condition){
if(condition){
element.css('color','red');
}
else{
element.css('color','black');
};
});
}
}
});
注意指令名称是testCaserather而不是testcase,范围:{‘condition’:’=’},位确保条件属性同步并可用作scope.condition,并且watch每次在第一个表达式计算第二个参数更改值。 JsFiddle over here。
也许你也应该看看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>