Search code examples
javascripthtmlcssangularjsng-class

Rotate Styles using Angular ng-if


Still learning angular, but having issues rotating styles. Ultimately, I want the first record to be blue, the second to be white, the third blue, the fourth white, etc...

Right now my order is (incorrect): Record 1 Blue Record 3 blue Record 2 white Record 4 white

Any ideas what could be the issues?

HTML

<div id="dashboard" style="width: 1100px;" ng-controller="controller4">

<div class="blue" ng-repeat="metrics in dashboard" ng-if="($index % 2 == 0)">
 <div align="center">
  <h3>{[{metrics.value}]}</h3>
  <span class=dashboardtext>{[{metrics.name}]}</span>
 </div>
</div>

<div class="white" ng-repeat="metrics in dashboard" ng-if="($index % 2 != 0)">
 <div align="center">
  <h4>{[{metrics.value}]}</h4>
  <span class=dashboardtext>{[{metrics.name}]}</span>
 </div>
</div>


</div>

JS

var dashboard = [

{

value: 15, 
name: "Total Completed"

},


{

value: 1200, 
name: "Additional Widgets Sold"

},


{

value: 16, 
name: "Projects"

},

{

 value: 5, 
 name: "Average Days"

 }


];




myApp.controller('controller4', function($scope) {


$scope.dashboard = dashboard;



});

Solution

  • ng-class-even & ng-class-odd directive perfectly suits your need.

    ng-class-even -> Add a class value to DOM classList object when $index is even

    ng-class-odd -> Add a class value to DOM classList object when $index is odd

    Markup

    <div ng-class="'blue'" ng-class-odd="'white'" ng-repeat="metrics in dashboard">
     <div align="center">
      <h3>{[{metrics.value}]}</h3>
      <span class=dashboardtext>{[{metrics.name}]}</span>
     </div>
    </div>