【问题标题】:AngularJS Infinite $digest Loop errorAngularJS 无限 $digest 循环错误
【发布时间】:2018-05-21 07:19:54
【问题描述】:

我正在尝试使用 ng-repeat 填充 div 列表。我还使用了一个有深度的框架(所以我可以浏览列表的元素)。

要设置这个深度,我需要调用getTotalDepths 函数,该函数使用tempIndex 值检查列表项的当前索引。如果它们不同,则应增加总深度,然后返回 totalDepths 值。

我运行后出现如下错误(约25000次):

未捕获的错误:[$rootScope:infdig]`http://errors.angularjs.org/1.6.10/$rootScope/infdig?

HTML:

<div style="display: inline-block;" ng-repeat="item in items">
    <div class="item-list" focusable data-focusable-depth="{{getTotalDepths($index)}}">
        <img class="img-fluid" ng-src="{{item.picture}}" />
    </div>
</div>

控制器:

$scope.totalDepths = -1;
var tempIndex = -1;
var x;

$scope.getTotalDepths = function (index) {
    x = $scope.totalDepths;
    if (tempIndex != index) {
        tempIndex = index;
        x = $scope.totalDepths += 1;
    }
    return x;
}

注意:当我在这一行增加totalDepths时会出现错误:

x = $scope.totalDepths += 1;

非常感谢任何帮助!

【问题讨论】:

  • AngularJS 为每个index 调用多次getTotalDepths 并且总是得到不同的结果,因为它不是纯函数并且有副作用 - $scope.totalDepths += 1。你应该重构你的代码。
  • 哦,我明白了,你有什么建议我可以做的吗?
  • 您能否展示所需的 HTML 结果示例,即data-focusable-depth 的值?
  • 这个 ng-repeat 在另一个 ng-repeat 中。目标是在每个列表的所有列表项中具有相同的深度编号。例如:List1:所有data-focusable-depth="0" List2:所有data-focusable-depth="1"等...

标签: angularjs angularjs-ng-repeat angularjs-infdig


【解决方案1】:

在@Slava 的帮助下,我解决了这个问题。

以我的方式调用 getTotalDepths() 是一个很大的错误,因为 Angular 在每个循环中都会调用它,并且函数每次都返回不同的结果。

我通过简单地调用 ng-init 中的函数来修复它,如下所示:

<div style="display: inline-block;" ng-repeat="item in items" ng-init="depth = getTotalDepths($index)">
    <div class="item-list" focusable data-focusable-depth="{{depth}}">
        <img class="img-fluid" ng-src="{{item.picture}}" />
    </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    相关资源
    最近更新 更多