Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$watchCollection() with Nested Arrays

I have a nested array of the form :

$scope.itinerary = 
    [
        [
          {name:'x'},
          {name:'y'},
          {name:'z'}
        ],
        [
          {name:'a'},
          {name:'b'},
          {name:'c'}
        ]
    ]

And I am doing a $watchCollection using the following :

$scope.$watchCollection(function () {
            return $scope.itinerary;
        }, 
        function () {
            console.log("Changed")
        }
);

But the console.log() is only executed if one of the sub array is deleted or a new array is inserted. If I move an element from One array to another, nothing happens. (eg when I move {name:'a'} from one array to another, nothing happens). How do I put a watch on the nested Array ?

like image 318
Kyuubi Avatar asked Jan 09 '23 20:01

Kyuubi


1 Answers

Use deep watch The $watch() function takes a third, optional argument for "object equality." If you pass-in "true" for this argument, AngularJS will actually perform a deep-object-tree comparison. This means that within each $digest, AngularJS will check to see if the new and old values have the same structure (not just the same physical reference). This allows you to monitor a larger landscape; however, the deep object tree comparison is far more computationally expensive.

$scope.$watch('itinerary',function (newVal,oldVal) {
          console.log(newVal)      

 },true);
like image 129
Narek Mamikonyan Avatar answered Jan 20 '23 07:01

Narek Mamikonyan