fypfyp fypfyp - 6 months ago 43
AngularJS Question

Angular - Incrementing value produces digest error

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.


<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;">


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

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.




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;">

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).