angularjs: $scope.$watch does not work inside forloop

The log under $watch returns undefined for both newV and OldV, but log before the watch returns the right property of the object. I have attached the results of first log that shows the data structure. I am trying to add a listener to the amount property inside contributors array.

for(var j = 0; j < vm.project.localCosts.length; j++) {
              console.log( vm.project.localCosts[j]);
              for (var k=0; k < vm.project.localCosts[j].contributors.length; k++) {
                console.log(vm.project.localCosts[j].contributors[k]);
                $scope.$watch('vm.project.localCosts[j].contributors[k].amount',function(newV,OldV){
                  console.log(newV,OldV);
                })
              }
            }

Answers


replace

'vm.project.localCosts[j].contributors[k].amount' 

with

'vm.project.localCosts[' + j + '].contributors[' + k + '].amount'

but i do not think you should be generating watches like this as it is a lot of overhead. maybe you can tell us what you are actually trying to accomplish

most likely this would be better

HTML

<div ng-app="demo">
  <table ng-controller="demoController">
    <tr ng-repeat="localCost in vm.project.localCosts">
      <td ng-repeat="contributor in localCost.contributors">
        <input ng-change="callback(localCost.contributors[$index], contributor, $index, $parent.$index)" type="text" ng-model="localCost.contributors[$index]" />
      </td>
    </tr>
  </table>
</div>

Javascript

var app = angular.module("demo", []);

app.controller("demoController", function($scope) {
  $scope.vm = {
    project: {
      localCosts: [{
        contributors: ["a", "b", "c"]
      }, {
        contributors: ["e", "f", "g"]
      }, {
        contributors: ["h", "i", "j"]
      }]
    }
  };

  $scope.callback = function(newValue, oldValue, i, j) {
    console.log(i, j, oldValue, newValue);
  };
});

Here is a code pen that does what you might want to do

http://codepen.io/anon/pen/BKLEME?editors=1010


Need Your Help