Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 308
Will Strohl Avatar asked Mar 16 '26 09:03

Will Strohl


1 Answers

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.

like image 86
m59 Avatar answered Mar 18 '26 23:03

m59



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!