如何在指令的属性中查看属性

编程入门 行业动态 更新时间:2024-10-25 16:23:42
本文介绍了如何在指令的属性中查看属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-22 00:18:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1012533.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   指令   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!