gpt4 book ai didi

javascript - 调用 $watchCollection 时 Angular $digest 无限循环

转载 作者:行者123 更新时间:2023-11-30 12:23:10 25 4
gpt4 key购买 nike

我想观察一个对象 x 以查看它的任何属性是否发生变化。属性是复选框。如果用户选中该框,它将选中的属性 (prop1) 更改为 1。

每个属性都有特定的内容,因此如果启用,它应该扩展包含元素的高度以说明新内容。

        $scope.x = {
prop1: 0,
prop2: 0,
prop3: 0,
prop4: 0,
};

我观察 x 是否有任何变化。如果是,则更新元素的高度:

    $scope.$watchCollection('x', function(embed){
$scope.x.height = $scope.getHeight();
});

调用获取高度,调用checkOptions()给元素增加指定的缓冲空间:

    $scope.getHeight = function () {
$scope.checkOptions();
return Math.ceil(($scope.totalElements / $scope.totalCols) * elementHeight);
};

$scope.checkOptions = function () {
if ($scope.x.prop1 === 1) {
elementHeight += 50px;
}
...other properties

HTML 使用复选框,检查真/假:

        <fieldset class="modal-checkbox">
<input type="checkbox"
id="element-prop1"
ng-model="x.prop1"
ng-true-value="1"
ng-false-value="0">
<label for="element-prop1">
<span>Element Prop 1</span>
</label>
</fieldset>

当我点击复选框时,它会不断增加高度,最后:

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! Watchers fired in the last 5 iterations: [[{"msg":"fn: regularInterceptedExpression","newVal":39,"oldVal":38},{"msg":"fn: expressionInputWatch","newVal":"6168","oldVal":"6006"}],'

我检查了Angular $watchCollection ,它似乎完全符合我的要求...观察 x 对象中的集合以查找更改...

$digest说:

Processes all of the watchers of the current scope and its children. Because a watcher's listener can change the model, the $digest() keeps calling the watchers until no more listeners are firing. This means that it is possible to get into an infinite loop.

我不明白为什么会出现循环。

最佳答案

您的 watch 功能有问题。每当您更改 $scope.x.height 时,它都会检测到 x 已更改并再次触发 watch 。

要么将该高度属性移出 x 并将其放在其他位置,要么确保无论您运行多少次 getHeight(),该值都不会不同。

顺便说一下,当您使用 ng-true-value 或 ng-false-value 时,该值将是一个字符串。

关于javascript - 调用 $watchCollection 时 Angular $digest 无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30359772/

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