2015-10-20 55 views
3

假設您有一個簡單的列表,可以是一個或10個項目。你不知道。您需要以常規的交替模式顯示5個CSS類。什麼是最好的方法來做到這一點?AngularJS中的替代多個CSS類

示例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; 
} 

沒有人有最佳方式的點子,以保證類始終交替,考慮這個例子嗎?

回答

4
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.

+1

巧妙...謝謝! :) –

+1

順便說一句,它的作品非常漂亮。 (對於那些未來可能會閱讀的人) –