AngularJS 10 $ digest () iterations achieved by generating random values

I have a directive that builds a list, and I draw each element with a different color on the fly, for example:

$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, for example:

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

but when the template compiles, I get the following:

 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 does my random color make it do this and how do you feel about something like that outside the color assignment of this object and refer to it like that.

+3
source share
2 answers

Like @doodeec, I redirect colorfn to pass the element, iteration, for example:

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

and in colorfn I installed it or said if it already returned it instead ...

$scope.color = function (item) {
    if (item.color) {
        return item.color;
    }

    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)];
    }

    // assign the color so it doesn't freak out
    item.color = color;

    return color;
};
0
source

, color ...

+5

All Articles