I am reading a book where I have encountered following code (there is a 2D arrays called products which has 3 rows)-
html
<div unordered-list="products" list-property="price | currency"></div>
and JS
angular.module("exampleApp", [])
.directive("unorderedList", function () {
return function (scope, element, attrs) {
var data = scope[attrs["unorderedList"]];
var propertyExpression = attrs["listProperty"];
if (angular.isArray(data)) {
var listElem = angular.element("<ul>");
element.append(listElem);
for (var i = 0; i < data.length; i++) {
var itemElement = angular.element('<li>');
listElem.append(itemElement);
var watcherFn = function (watchScope) {
return watchScope.$eval(propertyExpression, data[i]);
}
scope.$watch(watcherFn, function (newValue, oldValue) {
itemElement.text(newValue);
});
}
}
}
})
The book says, "AngularJS evaluates the three watcher functions, which refer to data[i] after the loop terminates". "By the time loop terminates, the value of i is 3, and this means that all three watcher functions try to access an object in the data array that doesn’t exist, and that’s why the directive doesn’t work".
The watcher function is inside the loop and called from scope.$watch so why it is so?