village
village

Reputation: 85

AngularJS Error: $rootScope:infdig

Error occurs in the following code of 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

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

Or error of the nest of the array? Cause is unknown.

Upvotes: 2

Views: 3103

Answers (2)

Tyler.z.yang
Tyler.z.yang

Reputation: 2450

You'd better to change your code into this:

In your controller:

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

In your 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>

Cause each time you use ng-repeat render a element, it will invoke list(). And inside ng-repeat directive it will watch your list() return result.

Each time you invoke list() it will return a new object.

Then this will trigger ng-repeat watchCollection to invoke listener. Then invoke $digest too much times, throw the error.

Here is ngRepeat watchCollection source code. 'rhs' is your data to repeat.

Suggest you to use the chrome debug tool to find out what happen inside of ngRepeat by youself. This can make you understand angular. : )

Upvotes: 0

Michael
Michael

Reputation: 3326

I think that using a function in ngRepeat makes angularjs call it for every element it finds, making it go in an infinite loop.

You could do the following:

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

so it is gonna work. There was another problem. The list() function is returning an object, not an array. Also, the second ngRepeat, is not breaking the code, but is not useful, because there aren't any nested arrays. Here's a working fiddle: http://jsfiddle.net/5sek867y/2/

Upvotes: 3

Related Questions