码迷,mamicode.com
首页 > 其他好文 > 详细

How to watch property in attrs of directive

时间:2017-05-05 18:35:06      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:change   binding   ret   count   rom   long   int   min   iso   

Q:

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.

How can I have a directive run a function each time that attr value changes?

 

A:

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:

Interpolating the attribute

Inside your directive, set the scope property as following (it will be isolated so):

scope: { 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.

How to watch property in attrs of directive

标签:change   binding   ret   count   rom   long   int   min   iso   

原文地址:http://www.cnblogs.com/qook/p/6814114.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!