[英]AngularJS Updating attribute in directive linking function dynamically
I have a directive that receives a string, which I would like the directive to then modify and add as an attribute's property. 我有一个接收字符串的指令,我希望该指令随后进行修改并添加为属性的属性。
HTML 的HTML
<div directive ng-class="" otherAttribute="hello"></div>
JS JS
.directive('directive', function () {
return {
link: function (scope, elem, attrs) {
var classList = "{active: attrs.otherAttribute == 'hello'}";
attrs.ngClass = classList;
console.log(attrs);
}
}
})
This does seem to add the properties to the class property of the attrs
object: 这似乎确实将属性添加到
attrs
对象的class属性中:
console.log(attrs);
$$observers: Object
$attr: Object
ngClass: "{active: attrs.otherAttribute == 'hello'}"
otherAttribute: "hello"
__proto__: Object
But the DOM is not updated. 但是DOM不会更新。 I've tried
$compile
, but that does not update the class attribute on the DOM either. 我已经尝试过
$compile
,但这也不会更新DOM上的class属性。
What am I missing? 我想念什么? Many thanks!
非常感谢!
You can use the directive element to modify a css class. 您可以使用指令元素来修改css类。
Working example of your code: http://jsfiddle.net/egrendon/vvnu5yLx/1/ 您的代码的工作示例: http : //jsfiddle.net/egrendon/vvnu5yLx/1/
app.directive('directive', function () {
return {
link: function (scope, element, attrs) {
scope.classList += "class1 class2";
element.addClass(scope.classList);
console.log(attrs);
}
}
});
You can use interpolation and reference directive scope 您可以使用插值和引用指令范围
<div directive class="class1 {{classList}}" otherAttribute="hello"></div>
link: function (scope, elem, attrs) {
scope.classList = "class2";
}
Pay attention that in your code there is an error, you reference an undefined scope.classList
with an +=
operator, resulting in undefinedclass1 class2
literal. 请注意,在您的代码中有一个错误,您使用
+=
运算符引用了一个未定义的scope.classList
,从而导致了undefinedclass1 class2
文字。 I suppose this might be a typo in example... 我想这可能是示例中的错字...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.