0

I want to attach watch on order. I am not sure how to add watch to variable inside list of dict. Inside controller,

cart_list = [{'order':'single'},{'order':'single'},{'order':'twice'}];

for (var i = 0; i < $scope.cart_list.length; i++) {
    $scope.$watch('cart_list[i].order', function() {
        console.log("Inside watch");
        if($scope.cart_list[i].order=='single'){
            console.log("with single order");
        }
    }
}

This gives me error,

TypeError: Cannot read property 'order' of undefined
Netro
  • 7,119
  • 6
  • 40
  • 58

2 Answers2

2

The only way i can think of making this watch work is by using function expression in the watch. The code becomes like

for (var i = 0; i < $scope.cart_list.length; i++) {
    setupWatch($scope.cart_list[i]);
}

function setupWatch(item) {
   $scope.$watch(function () {
            return item
        }, function (newValue, oldValue) {
            console.log("Inside watch");
            if (newValue.order == 'single') {
                console.log("with single order");
            }
        }, true);
}

I have not tried it, but i think this should work.

Also i am added strict object equality as the last parameter.

Chandermani
  • 42,589
  • 12
  • 85
  • 88
0

I will suggest to watch the entire collection rather than watching each object separately.

I hope this may help:

 $scope.$watchCollection("cart_list", function(newV, oldV){
     if(newV and newV.length > 0)
     {
       // do your stuff
       for(var i=0; newV.length; i++)
       {
          if(newV[i].order == "single")
            console.log("with single order");
       }
     }
 }, true);
Yashika Garg
  • 2,346
  • 2
  • 15
  • 17
  • the problem with this approach is, it does not watch array items for change, so even if `order` value changes the watch is not fired. – Chandermani Apr 28 '15 at 11:32
  • It will do item watch, I am sure of it.. as we are using Equality depth watch, with "true" attribute at the end. Have you tried it? – Yashika Garg Apr 28 '15 at 11:36
  • Or possibly you can $watch on collection with true as third argument, instead of $watchCollection http://stackoverflow.com/questions/14712089/how-to-deep-watch-an-array-in-angularjs – Yashika Garg Apr 28 '15 at 11:38
  • I have not tried but as per documentation there is no deep equality watch, https://docs.angularjs.org/api/ng/type/$rootScope.Scope – Chandermani Apr 28 '15 at 11:39
  • Thanks. `$watchCollection` is new to me. I will look into this. @Chandermani solution works for me. – Netro Apr 29 '15 at 04:03