2
votes

I am using a ng-class function in an element in ng-repeat. And I am getting this error. I am trying to pick a random class from the array. How do I solve this?

<div class="col-lg-4" ng-repeat="client in allClients">
<div class="someClass" ng-class="getClass()">
//some data
{{client.name}}
</div>
</div>

And this is my JS code.

$scope.getClass = function() {
var classArray = ['infobox1', 'infobox2', 'infobox3', 'infobox4', 'infobox5', 'infobox6'];
return classArray[Math.floor(Math.random() * classArray.length)];
}

The error goes on. Watchers fired in the last 5 iterations: [[{"msg":"getBackgroundClass()","newVal":"infobox4","oldVal":"infobox6"},{"msg":"getBackgroundClass()","newVal":"infobox4","oldVal":"infobox5"},{"msg":"getBackgroundClass()","newVal":"infobox1","oldVal":"infobox4"},{"msg":"getBackgroundClass()","newVal":"infobox5","oldVal":"infobox1"},{"msg":"getBackgroundClass()","newVal":"infobox1","oldVal":"infobox4"},{"msg":"getBackgroundClass()","newVal":"infobox6","oldVal":"infobox4"},{"msg":"getBackgroundClass()","newVal":"infobox1","oldVal":"infobox5"},{"msg":"getBackgroundClass()","newVal":"infobox1","oldVal":"infobox2"},{"msg":"getBackgroundClass()","newVal":"infobox1","oldVal":"infobox4"}],[{"msg":"getBackgroundClass()","newVal":"infobox6","oldVal":"infobox4"},{"msg":"getBackgroundClass()","newVal":"infobox1","oldVal":"infobox4"},{"msg":"getBackgroundClass()","newVal":"infobox4","oldVal":"infobox1"},{"msg":"getBackgroundClass()","newVal":"infobox5","oldVal":"infobox1"},{"msg":"getBackgroundClass()","newVal":"infobox4","oldVal":"infobox5"},{"msg":"getBackgroundClass()","newVal":"infobox2","oldVal":"infobox6"},{"msg":"getBackgroundClass()","newVal":"infobox6","oldVal":"infobox1"},{"msg":"getBackgroundClass()","newVal":"infobox6","oldVal":"infobox1"},{"msg":"getBackgroundClass()","newVal":"infobox4","oldVal":"infobox1"

2

2 Answers

1
votes

How often do you want to pick a random class? Currently, you have created an infinite loop because angular keeps noticing the class changed, runs a digest cycle to watch out for other changes, finds that the class changed again, runs a digest cycle to watch out for other changes, finds that the class changed again, and so on ...

You way want to pick the random value once, and stick with it for a while:

$scope.randomClass = classArray[Math.floor(Math.random() * classArray.length)]

(feel free to execute the above code as often as you want to see a new value)

0
votes

Here is the working example http://plnkr.co/edit/pl3W5uNofz123EJZnMT8

I made a classes array when I have the array with all my values in allClients, and then used that array to assign the classes

$scope.allClients = [{name: 'client'}, {name: 'client2'}, {name: 'client3'}];
  var classes = $scope.allClients.map(function(client) {
    var classArray = ['infobox1', 'infobox2', 'infobox3', 'infobox4', 'infobox5', 'infobox6'];
    return classArray[Math.floor(Math.random() * classArray.length)];
  });