我尝试编写自定义指令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;
}
}
}
});
但是当我传递param" active"
时,目录不会设置类答案 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