Atula Atula - 7 months ago 47
Javascript Question

Randomly Color Divs inside ng-repeat with unknown number of Items

I have data(say a list of items) and it is coming from $http.get request. I want to change the color of divs containing the items under ng-repeat div. The number of items are random.

My code

controller.js

$http.post("ServerUrl")
.success(function(data) {
$scope.data = data;
})
.error(function(err) {
alert(err);
})


template

<div ng-repeat="data in data">
{{data}}
</div>


What I want

enter image description here

What I have tried

Well I tried to put some colors in $scope and repeated them in template but if I have put 5 color in $scope then it is coloring only 5 div in template(working as expected).
So I want a way where I can repeat the color randomly for any number of items returning from $http request.

Answer

You can define if you want some specific colors and then make them repeat.

 $scope.colorCodeArray = [
         "#339E42",
         "#039BE5",
         "#EF6C00",
         "#A1887F",
         "#607D8B",
         "#039BE5",
         "#009688",
    ];


  <div ng-repeat="data in data">
  <div ng-style="{background: colorCodeArray[$index % colorCodeArray.length]}" >{{data}}</div>
    </div>