0

I'm trying to populate a list of divs using ng-repeat. I'm also using a framework that has depths (so i can navigate through the list's elements).

To set this depth I need to call getTotalDepths function that checks the current index of the list item with a tempIndex value. If they are different it should increase the total depths and then return the totalDepths value.

After I run it, the following error occurs (about 25000 times):

Uncaught Error: [$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>

Controller:

$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;
}

Note: The error occurs when i increase totalDepths in this line:

x = $scope.totalDepths += 1;

Any help is deeply appreciated!

Saeed
  • 5,413
  • 3
  • 26
  • 40
iSpithash
  • 56
  • 9
  • AngularJS calls `getTotalDepths` several times for each `index` and always gets different resuts, because it is not pure function and has side effects - `$scope.totalDepths += 1`. You should refactor your code. – Slava Utesinov May 21 '18 at 08:19
  • Oh I see, is there something you suggest I could do? – iSpithash May 21 '18 at 08:23
  • Can you show example of desired HTML result, i.e. values of `data-focusable-depth`? – Slava Utesinov May 21 '18 at 08:24
  • This ng-repeat is inside an other ng-repeat. The goal is to have the same depth number in all list items of each list. ex: List1: all `data-focusable-depth="0"` List2: all `data-focusable-depth="1"` etc... – iSpithash May 21 '18 at 08:39

1 Answers1

0

With the help of @Slava I solved the problem.

Calling the getTotalDepths() the way I did was a big mistake as Angular calls it in every cycle, and the function returns different result every time.

I fixed it by simply calling the function inside the ng-init like so:

<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>
iSpithash
  • 56
  • 9