Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS 10 $digest() iterations reached when generating random values

Tags:

angularjs

I've got a directive that builds a list and I paint each item with a different color on the fly like:

$scope.color = function () {
    var letters = '012345'.split('');
    var color = '#';
    color += letters[Math.round(Math.random() * 5)];
    letters = '0123456789ABCDEF'.split('');
    for (var i = 0; i < 5; i++) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
};

then I call it in the template like:

<li ng-repeat="item in list">
   <a ng-style="{ background: color() }">{{item.acronym}}</a>
</li>

but when the template compiles i get this:

 Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
 Watchers fired in the last 5 iterations: [["{ background: color() }; newVal: {\"background\":\"#455116\"}; oldVal: {\"background\":\"#2B1EDC\"}"],["{ background: color()...<omitted>...5D 

Obviosuly $digest is in a loop but why would my random color be causing this to do this and how do you address something like this outside of assigning the color to the object and referencing it like that.

like image 766
amcdnl Avatar asked Dec 22 '25 13:12

amcdnl


1 Answers

It's because the color function gets called in every digest cycle and in every function call it's generating different color... so it's changing multiple times in a second

like image 112
doodeec Avatar answered Dec 24 '25 12:12

doodeec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!