How to watch property in attrs of directive

后端 未结 5 1483
难免孤独
难免孤独 2020-12-25 14:44

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 dire

5条回答
  •  一整个雨季
    2020-12-25 15:17

    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.

提交回复
热议问题