use*_*522 4 for-loop watch angularjs
如果我动态地注册监视事件(在我的情况下在for循环中),则在角度中,手表不起作用.请看一个小提琴.有任何想法吗?
var myApp = angular.module('myApp',[]);
function MyCtrl($scope, $parse) {
// 1. binding watch inside loop (doesn't work):
$scope.aaa = 1;
$scope.bbb = 2;
$scope.dependsOn = [
function () { return $scope.aaa; },
function () { return $scope.bbb; }
];
for (var i = 0; i < $scope.dependsOn.length; i++) {
$scope.$watch(
function () {
return $scope.dependsOn[i];
},
function (newVal) {
if (newVal !== undefined) {
console.log("doesn't work");
}
}
);
}
$scope.aaa = 5;
$scope.bbb = 6;
// binding watch not inside loop (works):
$scope.ccc = 1;
$scope.ddd = 2;
$scope.dependsOn = [
function () { return $scope.ccc; },
function () { return $scope.ddd; }
];
$scope.$watch(
function () {
return $scope.dependsOn[0];
},
function (newVal) {
if (newVal !== undefined) {
console.log("works");
}
}
);
$scope.$watch(
function () {
return $scope.dependsOn[1];
},
function (newVal) {
if (newVal !== undefined) {
console.log("works");
}
}
);
$scope.ccc = 5;
$scope.ddd = 6;
}
Run Code Online (Sandbox Code Playgroud)
您遇到的问题是因为您正在i关闭中捕获变量.然后i增加到值2并退出循环,每个代理i在实际执行委托时将具有2作为其值.
演示:http: //jsfiddle.net/df6L0v8f/1/ (添加:)
$scope.$watch(
function () {
console.log(i);
return $scope.dependsOn[i];
},
function (newVal) {
if (newVal !== undefined) {
console.log("doesn't work");
}
}
);
Run Code Online (Sandbox Code Playgroud)
您可以通过使用自调整闭包来捕获迭代时的值并为您的委托维护该值来解决此问题和变量提升问题.
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());
}
}
);
}
Run Code Online (Sandbox Code Playgroud)