How to redirect a directive when changing scope in AngularJS

Say you have something like this:

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

And you want mydirective to be applied when changing $ scope.boundtoscope. How do you click Angular to reapply the directive?

+4
source share
1 answer

In your linking link $ function, see 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 the boundtoscope is an array or map of objects, and you want to look for changes in the elements in the array / object, set the objectEquality parameter to true to execute the "small" hours (i.e. compare the array / object for equality, not 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 
+8
source

All Articles