1

I'm currently facing the infinite digest loop error which I need some help/advice with.

So I've read the docs as well as posts on StackOverflow and I think i understand the issue - if someone could also confirm - it's essentially because something in the $scope is changing a fair number of times.

Assuming what I understand above is correct - I'm unsure on how to solve this and any advice would be appreciated.

The code I have looks like this:

HTML Side

<ul class="no-bullet" ng-repeat=“person in persons”>
   <li>
     <div class="progressBar" ng-style="{background: styleBuilder(person.options)}"></div>
   </li>
</ul>

And in my controller (for context: personsArray is what is passed from the HTML side and the for loop is used to update an array that contains numbers into percentages so ['classA: 8', 'classB: 2'] becomes ['classA: 75', 'classB: 25'] (I've tested this and it works)

  $scope.styleBuilder = function (optionsArray){

    for (var index in personsArray){
      proportion = parseInt(personsArray[index].split(':')[1])/sumOfAllValues;
      if (isNaN(proportion) ){
        proportion = 0;
       }

       personsArray[index] = personsArray[index].substring(0, personsArray[index].indexOf(':'));
       personsArray[index] = personsArray[index] + ' : ' + proportion*100;

    }

}

Thanks.

2
  • Its required - so the data I get from (person.options) in that ng-repeat is used to style accordingly. Commented Feb 24, 2016 at 11:54
  • It goes away naturally - the error occurs at the line: personsArray[index] = personsArray[index] + ' : ' + proportion*100; Commented Feb 24, 2016 at 12:01

2 Answers 2

2

The problem is in this line (in digest cycle as @Raulucco explained):

ng-style="{background: styleBuilder(person.options)}"

Try ng-init:

<li ng-init="bg = styleBuilder(person.options)">
   <div class="progressBar" ng-style="{background: bg}"></div>
</li>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks - and would you say the reason below by Raulucco is correct to why this solution works?
@userMod2 Yes, ng-init creates scope property from function call result and no problem because of $watch
1

The issue is that you are changing the elements inside the array at the same time that you are looping through the array. Angular binds a watch to each options attribute because you are accessing the property inside the loop, you change it a digest cycle is fired. To avoid it in this example do not change the options property just return the new style or loop through the array and change the options before assign it to the $scope.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.