【问题标题】:AngularJS Error: $rootScope:infdigAngularJS 错误:$rootScope:infdig
【发布时间】:2014-11-05 17:37:20
【问题描述】:

AngularJS的以下代码出现错误。

test01.js

var MyApp = angular.module('moduleName', []);
MyApp.controller('NameCtrl', ['$scope', function ($scope) {
    $scope.list = function() {

        return {"1": {id: 1, name: "aaa"},
                "2": {id: 2, name: "bbb"},
                "3": {id: 3, name: "ccc"}};
    }
}]);

test01.html

<div class="container">
    <div class="jumbotron">
        <h2>test01!</h2>
    </div>
    <div ng-controller="NameCtrl">
        <table class="table table-striped">
            <tr ng-repeat="list in list()">
                <td ng-repeat="nake in list">{{nake.id}}</td>
            </tr>
        </table>
    </div>
</div>

错误

Error: [$rootScope:infdig] http://errors.angularjs.org/1.3.1/$rootScope/infdig?p0=10&p1=%5B%5B%22fn%3A…Breturn%20z(e)%3Ff%3Ae%7D%3B%20newVal%3A%2034%3B%20oldVal%3A%2031%22%5D%5D
Uncaught Error: [$rootScope:infdig] http://errors.angularjs.org/1.3.1/$rootScope/infdig?p0=10&p1=%5B%5B%22fn%3A…Breturn%20z(e)%3Ff%3Ae%7D%3B%20newVal%3A%2034%3B%20oldVal%3A%2031%22%5D%5D angular.js:14078

还是数组嵌套错误? 原因不明。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    我认为在 ngRepeat 中使用函数会使 angularjs 为它找到的每个元素调用它,使其进入无限循环。

    您可以执行以下操作:

    <table class="table table-striped" ng-init="list = list()">
        <tr ng-repeat="element in list">
    

    所以它会起作用的。 还有一个问题。 list() 函数返回一个对象,而不是数组。 此外,第二个 ngRepeat 不会破坏代码,但没有用,因为没有任何嵌套数组。 这是一个工作小提琴: http://jsfiddle.net/5sek867y/2/

    【讨论】:

      【解决方案2】:

      你最好把你的代码改成这样:

      在您的控制器中:

      $scope.lists = {  // can change to array
            "1": {id: 1, name: "aaa"},
            "2": {id: 2, name: "bbb"},
            "3": {id: 3, name: "ccc"}
      };
      

      在您的 html 中:

      <div class="container">
          <div class="jumbotron">
              <h2>test01!</h2>
          </div>
          <div ng-controller="NameCtrl">
              <table class="table table-striped">
                  <tr ng-repeat="list in lists">
                      <td ng-repeat="nake in list">{{nake.id}}</td>
                  </tr>
              </table>
          </div>
      </div>
      

      因为每次使用 ng-repeat 渲染元素时,它都会调用 list()。在 ng-repeat 指令中,它会观察你的 list() 返回结果。

      每次调用 list() 都会返回一个新对象。

      然后这将触发 ng-repeat watchCollection 来调用监听器。然后调用$digest太多次,抛出错误。

      Here is ngRepeat watchCollection source code. 'rhs' 是您要重复的数据。

      建议你自己使用chrome调试工具来看看ngRepeat里面发生了什么。这可以让你理解角度。 :)

      【讨论】:

      • 投反对票的人能给我一个建议吗?
      猜你喜欢
      • 1970-01-01
      • 2016-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多