Reputation: 53991
I have a directive (Let's call it B) used inside another directive template (Let's call it A) as follows:
<cr-carousel items="carouselData"></cr-carousel>
The carouselData
property is an array of objects.
Inside my controller for directive A I have a hook into an event in which I modify carouselData
through Array.prototype.splice.apply
:
$scope.$on('carousel.keypress', function (event, data) {
... some logic and branching
Array.prototype.splice.apply($scope.carouselData, [someIndex, 0].concat(newItems));
As you can see, I'm inserting new carousel items into the carousel at some index.
The carousel itself contains a repeater directive:
<li ng-repeat="item in carouselData">
which seems to be working just fine. Inserting new items into the carousel causes new items to appear in the list on the HTML end of things.
The problem I'm having is that the $watch
within directive B that's watching carouselData
doesn't trigger when the new items are inserted.
$scope.$watch($attrs.items, function(value) {
console.log("The elements for the carousel just changed.", value);
});
I see the message show a couple of times when the page loads, but I get nothing when the new items are inserted. I've tried wrapping the splice
code in a $timeout
and also tried calling $scope.$apply()
to see if that would trigger anything, and nadda.
Can anyone explain what's going on here?
Here's a JSFiddle of the issue: http://jsfiddle.net/urdjrqvL/
Notice that Here happened
is only logged to the console the first time the values are updated. When the value of the property is update in the $timeout
, the items show in the HTML but the $watch
doesn't fire.
Upvotes: 1
Views: 61
Reputation: 123
instead of $scope.$watch
, use $scope.$watchCollection
in case of watching array changes. If you use $watch
, there is a third parameter which specifies whether to watch for changes in value or reference. Array.splice
only changes the array contents, not reference, so simple watch won't fire.
For details on $watch and $watchCollection, refer the correpsonding sections in this page-
https://docs.angularjs.org/api/ng/type/$rootScope.Scope
Upvotes: 3