Angular: watch not working inside loop
The problem you are experiencing is because you are capturing the variable i
in a closure. Then i
gets incremented to the value 2 and drops out of the loop, each of your delegates will have 2 as their i
value upon actually executing the delegate.
Demonstrates:http://jsfiddle.net/df6L0v8f/1/(Adds:)
$scope.$watch( function () { console.log(i); return $scope.dependsOn[i]; }, function (newVal) { if (newVal !== undefined) { console.log("doesn't work"); } });
You can fix this and the issue of variable hoisting by using a self calling closure to capture the value at the time of iteration and maintain that for your delegate.
http://jsfiddle.net/df6L0v8f/4/
for (var i = 0; i < $scope.dependsOn.length; i++) { var watchDelegate = (function(itemDelegate){ return function () { return itemDelegate; }; })($scope.dependsOn[i]); $scope.$watch( watchDelegate, function (newVal) { if (newVal !== undefined) { console.log(newVal()); } } ); }