![](/img/trans.png)
[英]AngularJS, Link function in directive, how to update attrs when clicking on a button?
[英]angularJS how to change attrs in directive's link
我在应用程式中设定进度
我想控制angular指令的进度
但是如何在指令的链接函数中更改data-value
和data-total
?
app.html
<div class="ui indicating small progress" data-value="39" data-total="50" plan-progress>
<div class="bar">
<div class="progress"></div>
</div>
</div>
在此html中,我想更改data-value
和data-total
我尝试这样:
app.js
todoApp.directive('planProgress', function() {
return {
link: function(scope, elem, attrs) {
attrs.value = 10
attrs.total = 20
elem.progress();
}
};
});
但这不起作用
所以我想知道如何在指令中更改它?
在链接函数中使用attrs.$set()
并重新编译该元素。 另外,不要忘记将$compile
服务注入到指令中。 在您的html中,您已将指令添加为属性,但未在指令定义的限制值中提及它。 您需要在指令定义中提及它。 参见下面的代码:
todoApp.directive('planProgress', function($compile) {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
attrs.$set('value', 10);
attrs.$set('total', 20);
$compile(elem)(scope);
}
};
});
只需使用:
attrs["data-value"] = 10;
attrs["data-total"] = 20;
您不想使用attrs.data-total = 20
因为-
会强制减去。
在JavaScript中使用x[keyName]
代替x.keyName
始终是合法的,并且当keyName是一个奇怪的键(例如**$^ùjsls*
或data-value
时,必须使用第二种表示法。 一个更有用的情况是键是变量。
最后一件事:您将始终重写编码器的输入。 它可能有道理,但不是很优雅。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.