{ return { template: require('./set-bid.html'), scope: { newOrder:" /> { return { template: require('./set-bid.html'), scope: { newOrder:" /> { return { template: require('./set-bid.html'), scope: { newOrder:"/>

How to watch directive attributes changes?

42 views Asked by At

I have a directive:

set-bid.js

app.directive("setBid", ($rootScope, Http, Toast) => {
  return {
    template: require('./set-bid.html'),
    scope: {
      newOrder: "<"
    },
    link: function($scope, element, attrs) {

      console.log(`$scope.newOrder:`, $scope.newOrder); // undefined

    }
  }
});

set-bid.html

{{newOrder}} <!-- nothing -->

parent.html

<set-bid new-order="newOrder"></set-bid>

As you can see, I send newOrder variable to the set-bid directive. However newOrder will be filled async.

I want the set-bid directive to watch for changes in this attribute. But I do not want to watch on each param like this:

$scope.$watch("newOrder", newOrder => console.log(newOrder));

This is tedious. I want that the whole directive will listen for changes in every param that it receives. Automatically. How this can be done?

I know I can do something like this: <set-bid ng-if="newOrder" ...></set-bid> but I need the variable to continously be watched, not just for the first time.

2

There are 2 answers

2
georgeawg On

Set the third argument to true:

$scope.$watch("newOrder", newOrder => console.log(newOrder), true);

That creates a "deep" watch.

For more information, see

0
ssc-hrep3 On

You could just pass one object instead of many params and watch this one (deeply). Then, you also don't have the problem that the watcher fires multiple times, even though you e.g. just wanted to switch all params together.

Another approach would be to use a $watchCollection() and watch multiple params together, but you would need them to be listed one by one.