Will Strohl
Will Strohl

Reputation: 1680

Alternate multiple CSS classes in AngularJS

Let's say you have a simple list that can be one or 10's of items. You don't know. You have 5 CSS classes that you want to display, in a regular alternating pattern. What would be the best way to do this?

Example HTML:

<div ng-repeat="item in items | orderBy: 'Title'">
    <div class="clearfix" ng-if="$index % 3 == 0"></div>
    <div class="col-sm-4">
        <div class="tile" ng-class="{ 'purple': expression1, 'red': expression2, 'green': expression3, 'blue': expression4, 'orange': expression5 }">
            <h3 class="title">{{item.Title}}</h3>
            <div>{{item.Description}}</div>
        </div>
    </div>
</div>

CSS

.tile.purple {
    background: #5133ab;
}
.tile.red {
    background: #ac193d;
}
.tile.green {
    background: #00a600;
}
.tile.blue {
    background: #2672ec;
}
.tile.orange {
    background: #dc572e;
}

Does anyone have an idea of the best way to ensure that the classes are consistently alternated, considering this example?

Upvotes: 3

Views: 409

Answers (1)

m59
m59

Reputation: 43785

angular.module('myApp', [])
.controller('MyCtrl', function($scope) {
  $scope.items = [1,2,3,4,5,6,7,8,9,10];
  // make an array of color classes
  $scope.colors = ['purple', 'red', 'green', 'blue', 'orange'];
})
;
<div ng-app="myApp" ng-controller="MyCtrl">
  <div ng-repeat="item in items">
    <!-- use modulus operator to pick the right class per item -->
    <div class="tile" ng-class="colors[$index % colors.length]">{{item}}</div>
  </div>
</div>

Click here for live demo.

Upvotes: 4

Related Questions