gpt4 book ai didi

javascript - Angular :对象数组中的 $watch 对象

转载 作者:行者123 更新时间:2023-11-28 18:31:34 24 4
gpt4 key购买 nike

例如,我有一个对象数组。

$scope.items = [
{id: 1, name: 'one'},
{id: 2, name: 'two'},
{id: 2, name: 'three'}
];

并在模板中有类似的内容

<div ng-repeat="item in items">
<input type="text" ng-model="item.name" />
</div>

我想添加 $watch 到此(用于跟踪输入中的更改)

$scope.$watch('item', function(newVal){}, true);

如果我想要在 newVal 项目中拥有像 {id: 1, name: 'one'} 这样的内容,我需要做什么?

不是对象数组! newVal 中仅更改了一个对象!我无法为 Controller 中数组的每个对象创建变量。

我尝试过类似的事情

for (var i = 0; i < $scope.items.length; i++) {
$scope.$watch('items[' + i = ']', function(newVal) {
console.log(newVal);
}, true);
}

但这是错误的。

最佳答案

你可以尝试类似的事情

for (var i = 0; i < $scope.items.length; i++) {
(function(k){
$scope.$watch(function(){
return $scope.items[k]
}, function(newVal) {
console.log(newVal);
}, true);
})(i);
}

注意:我没有测试上面的代码;

关于javascript - Angular :对象数组中的 $watch 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37882932/

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