gpt4 book ai didi

javascript - AngularJS $watchCollection 与 ng-repeat 结合

转载 作者:行者123 更新时间:2023-12-03 11:07:02 25 4
gpt4 key购买 nike

如果我直接在 ng-repeat 中使用输入字段,则在获取列表更改通知时遇到一些问题。否则我可以更改值并从 $watchCollection 获取通知。

一个简化的例子:

<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.js">
</script>
</head>
<body>
<section ng-app="myApp" ng-controller = "TestController">
<button ng-click = "pushToList()">Add number to list.</button>
<button ng-click = "changeFirstElement()">Change first element.</button>
<textarea ng-model = "log"></textarea>
<ul>
<li ng-repeat="item in list track by $index">
<input ng-model="item"> Value: <span ng-bind="item"></span>
</li>
</ul>
</section>
<script>
angular.module("myApp", [])
.controller("TestController", function($scope){
$scope.log = '';
$scope.list = $scope.list = [1];

$scope.pushToList = function() {
$scope.list.push(Math.random());
}

$scope.changeFirstElement = function() {
$scope.list[0] = Math.random();
}

$scope.$watchCollection(
'list',
function(currentValue, oldValue) {
$scope.log += [
'Current value:',
currentValue.toString(),
'Old value:',
oldValue ? oldValue.toString() : '',
'-----',
'',
].join('\n')
}
)
});
</script>
</body>
</html>

当我通过调用 $scope.list[0] = Math.random(); 进行更改时,$watchCollection 会“看到”,但当我使用输入字段时,更改会被忽略,或者“$watchCollection 没有看到”。为什么是这样?我还能做什么?

我知道我可以使用深度 $watch 来代替,但我很感兴趣如何使用 $watchCollection 来实现这一点。另外,如果我理解正确的话,性能会更好(请参阅 this question )。

编辑:

这是一个plunkr

当您单击“将数字添加到列表”时,$watchCollection 将看到更改,并且数组的当前内容将写入文本区域。当您通过单击“更改第一个元素”更改第一个数字时,$watchCollection 确实看到发生了更改,并再次将数组上的当前内容写入文本区域。当您使用 ng-repeat 放置的输入字段更改值时,其中的数组项为 ng-model。我希望如果我更改输入字段中的值,它将触发与单击“更改第一个元素”按钮时相同的行为:我希望 $watchCollection 应该看到发生了更改,并且我注册的函数应该写入数组的内容到文本区域。但这并没有发生。

最佳答案

问题不在 $watchCollection 中。 ng-repeat 为每个子范围创建范围,因此当您输入输入时,您仅在 ng-repeat 子范围中更改 item 属性,因为 item 是原始的。如果您有 $scope.list=[{value:1}] 您可以更改父范围中的值,更改子范围中的值,因为 list[0] 和 item 共享同一对象上的引用。但 watchCollection 仍然不会被触发,因为它只检测到浅层变化。

关于javascript - AngularJS $watchCollection 与 ng-repeat 结合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27802752/

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