问题描述
限时送ChatGPT账号..我有一个控制器,它有一个不时变化的计数器.
该计数器与指令的属性相关联,并在该指令的链接函数内读取.
I have a controller that has a counter that changes from time to time.
That counter is tied to an attribute of a directive and read inside the link function of that directive.
如何让指令在每次 attr 值更改时运行函数?
How can I have a directive run a function each time that attr value changes?
谢谢.
推荐答案
在你对应的 link
函数中:(假设你的属性被称为 counter
并且你的作用域变量是:范围
)
Inside your corresponding link
function: (assuming your attribute is called counter
and your scope variable is: scope
)
scope.$watch(attrs.counter, function (newTime) {
//do something with the new Time
});
其他方式,当然更有效的方式:
Other way, surely more efficient way:
在您的指令中,将 scope
属性设置如下(它将被隔离):
Inside your directive, set the scope
property as following (it will be isolated so):
scope: { counter: '@'}
只要调用 link
函数,就会自动观察 counter
提供的当前值.
The counter
would automatically be observed providing the current value as long as the link
function is called.
'@'
在这里比 '='
更好,因为我想您没有在指令中将计数器设置为新值,这意味着您只是阅读了它.实际上,=
对于双向数据绑定更有用,但您可能不需要它.
'@'
better than '='
here since you I suppose you don't set the counter to a new value in your directive, meaning you just read it. Indeed, =
is more useful for two-way data binding but you might not need it.
这篇关于如何在指令的属性中查看属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论