4
如果我動態註冊手錶事件(在我的情況下爲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;
}