Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reapply directive when scope is changed in AngularJS

Say you have something like this:

<div mydirective>
  {{boundtoscope}}
</div>

And you want mydirective to be applied on change of $scope.boundtoscope. How do you direct Angular to reapply the directive?

like image 452
Robert Christian Avatar asked Feb 17 '23 18:02

Robert Christian


1 Answers

In your directive's link function $watch the scope property:

myApp.directive('mydirective', function () {
  return {
    link: function (scope, element, attrs) {
      scope.$watch('boundtoscope', function(newValue) {
          alert('boundtoscope changed');
          // do something here
      });
    }
  }
});

If boundtoscope is an array or an object map, and you want to look for changes to items within the array/object, set the objectEquality argument to true to perform a "shallow" watch (i.e., compare the array/object for equality rather than for reference):

  scope.$watch('boundtoscope', function(newValue) {
      alert('boundtoscope changed')
  }, true);    // "shallow" compare

Angular 1.2 adds a new method for this, $watchCollection:

  scope.$watchCollection('boundtoscope', function(newValue) {
      alert('boundtoscope changed')
  });  // also does a "shallow" compare
like image 86
Mark Rajcok Avatar answered Feb 20 '23 08:02

Mark Rajcok