Reputation: 53850
I have a directive looking like this:
directive('parcelsCarousel',function () {
return {
restrict:'E',
replace:true,
transclude:true,
templateUrl:'/partials/parcels-carousel.html',
link:function (scope, element, attrs) {
scope.$watch('favoriteParcelsList', function (favoriteParcelsList) {
if (scope.favoriteParcelsList != undefined)
console.log(scope.favoriteParcelsList.length)
});
}
}
});
I push an item to favoriteParcelsList
from the controller, but the $watch doesn't run.
What can I do the wrong way? I am sure I am missing something small thing because I have a couple of other directives having similar structure and they work fine.
Upvotes: 0
Views: 169
Reputation: 117370
Seeing more code (ideally live, in a plunker) would be ideal to say for sure but I suspect that you want to add elements to the favoriteParcelsList
and have AngularJS picking up those changes. If so it needs to be noted that by default $watch
tracks identity of objects. If you want to track content of more complex objects you need to use deep-watch.
You can instruct AngularJS to deep-watch for changes by supplying third, boolean parameter to the $watch
method (notice true at the end):
scope.$watch('favoriteParcelsList', function (favoriteParcelsList) {
if (scope.favoriteParcelsList != undefined)
console.log(scope.favoriteParcelsList.length)
}, true);
Upvotes: 2