1

I have 4 different classes that need to be added to a div inside a ng-repeat.

<li ng-repeat="post in posts">
    <span class="color-RANDOM-VALUE">{{post.title}}</span>
</li>

Once I have the loop running, it should look like:

<li>
    <span class="color-blue">Title</span>
</li>
<li>
    <span class="color-yellow">Title</span>
</li>
<li>
    <span class="color-purple">Title</span>
</li>
<li>
    <span class="color-red">Title</span>
</li>

Any suggestions on the best way to do that?

Bruno Monteiro
  • 712
  • 6
  • 22
  • What is the current output you are getting from your ng-repeat? – Shane Oct 23 '15 at 17:57
  • So do you need a random number in a range, like 1-4 to pick a random color? If so, look at this for getting a random number: http://stackoverflow.com/questions/1527803/generating-random-numbers-in-javascript-in-a-specific-range – lintmouse Oct 23 '15 at 18:23

1 Answers1

0

AngularJS has a built in directive called ng-class. You can have your scope return random classes for the element to use as follows:

<li ng-repeat="post in posts">
    <span ng-class="getRandomColorClass()">{{post.title}}</span>
</li>
var colorArray = [ 'blue', 'purple', 'yellow', 'grey' ];

$scope.getRandomColorClass = new function() {
  return 'color-' + colorArray[Math.floor((Math.random() * colorArray.length))];
};
oachler
  • 1
  • 2