gpt4 book ai didi

angularjs - Angular : watch not working inside loop

转载 作者:行者123 更新时间:2023-12-04 23:00:31 25 4
gpt4 key购买 nike

如果我动态注册 watch 事件(在我的情况下是 for 循环),则 watch 无法工作。请看一下 fiddle 。有任何想法吗?

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;
}

fiddle

最佳答案

您遇到的问题是因为您正在捕获变量 i在一个封闭。然后i递增到值 2 并退出循环,您的每个代表将有 2 作为他们的 i实际执行委托(delegate)时的值。

证明:
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");
}
}
);

您可以通过使用自调用闭包在迭代时捕获值并为您的委托(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());
}
}
);
}

关于angularjs - Angular : watch not working inside loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26407481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com