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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With