Berry Berry - 9 days ago 5
Javascript Question

ng-class with function call that generate random string

I am using Materialize Library for my Angular app. The problem is i am trying to add random class name so that the background would be different for each tag.

<ul class="inline-list" ng-repeat="feature in features">
<li class="chip" ng-class="getColor()">{{feature}}</li>
</ul>


And my controller,

function ProjectsController($scope) {
$scope.features = ['React', 'Redux', 'Firebase'];
const colorClass = ['pink lighten-3', 'indigo lighten-2', 'lime accent-1',
'amber accent-2','grey darken-2', 'deep-orange darken-1', 'green accent-2',
'teal', 'purple', 'red darken-1'];
$scope.getColor = () => {
return colorClass[Math.floor(Math.random()*10)]
}
}


The browser throw an error as:


angular.js:10633 Error: [$rootScope:infdig]


Please give me some clue to solve this problem.

Answer

Seems like you get in infinite loop of $scope.digest().

Check documentation about [$rootScope:infdig] error:

I would suggest to rewrite your controller like this:

function ProjectsController($scope) {

   const colorClass = ['pink lighten-3', 'indigo lighten-2', 'lime accent-1',  'amber accent-2','grey darken-2', 'deep-orange darken-1', 'green accent-2', 
 'teal', 'purple', 'red darken-1'];


  function getColor() {
     return colorClass[
             Math.floor(Math.random() * 10 )
          ]
  }

  $scope.features = [
         { technology: 'React', color: getColor() },
         { technology: 'Redux', color: getColor() },
         { technology: 'Firebase', color: getColor() },
  ];
}

Also, you should edit yout HTML:

<ul class="inline-list" ng-repeat="feature in features">
    <li class="chip" ng-class="feature.color">{{feature.technology}}</li>
</ul>

Hope, it helps

Comments