How to watch property in attrs of directive

Viewed 40765

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?

Thanks.

5 Answers

I am using this aproach:

.directive('mydirective',
 [function (){
    return {
      ...
      scope: {
        id: '@',
      },
      controller: function ($scope, $element, $attrs) {
         $attrs.$observe('id', function(passedId) {
           /// do what is needed with passedId
         });
    ...

And the directive used and id passed like this:

<div mydirective id="{{someprop.id}}" />

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.

If you can, change the directive to isolated scope and use the = definition. This will set up a two-way binding for the scope property:

app.directive('myDirective', function() {

    return {
        scope: { counter: '=' }
    }
});
Related