Angular - Incrementing value produces digest error

138 Views Asked by At

I know the issue I'm having, but I can't figure out a way around it. No matter what I do, I get a digest error. The problem I believe, is calling the "getPlayerIcon" method within the ng-repeat.

HTML:

 <div class="col-md-2" ng-repeat="player in team.players">
   <img class="card-img-player" ng-src="/{{player.position}}/{{getPlayerIcon(player.position)}}" data-holder-rendered="true" style="height: 270px; width: 100%; display: block;">
 </div>

AngularJS:

$scope.getPlayerIcon = function(position) {
 if ($scope[position] === undefined)
   $parse(position).assign($scope, 1);

$scope[position]++;
return $scope[position];
}

"Player" contains a 'position' field which can be a Defender or Attacker. The 'getPlayerIcon' method takes in the position as a parameter, and then either creates a scope variable with that position name, either with a value of 1 if it's the first one it's come across that position, or increments it if it's an occurrence of that position.

The problem I'm having is that calling a method on ng-src changes the value everytime it's called in the ng-repeat, which results in the infamous indig digest error:

angular.js:68 Uncaught Error: [$rootScope:infdig] 10 $digest - `iterations reached. Aborting!`

How can I fix this? I have to increment because, for example, if there are 4 defenders and 4 attackers in the team.players, I want to be able to load images with Defender/1, Defender/2, Defender/3, Defender/4, Attacker/1, Attacker/2, Attacker/3, Attacker/4. Basically I need it to identify the position, and have a count of that position to pull out the correct image.

Help!

Thanks, FYP

1

There are 1 best solutions below

0
On BEST ANSWER

Just use the $index.

 <div class="col-md-2" ng-repeat="player in team.players track by $index">
   <img class="card-img-player" ng-src="/{{player.position}}/{{getPlayerIcon(player.position, $index)}}" data-holder-rendered="true" style="height: 270px; width: 100%; display: block;">
 </div>

This will give you the index of the current iteration in the loop and then there will be no need to do increments in your method (you can pass in the $index value instead and add one to it).