user2828701
user2828701

Reputation: 305

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;



});

Upvotes: 2

Views: 585

Answers (2)

mhodges
mhodges

Reputation: 11116

For simple even/odd, you can use the ng-class-even and ng-class-odd attributes. If you have a more complex situation with more values, use the below solution.

Create a filter and use it in the class attribute.

app.filter("classFilter", function () {
            return function (input) {
                var $class = "";
                switch(input % 2){
                    case 0:
                        $class = "blue";
                        break;
                    case 1:
                        $class = "white";
                        break;
                }
                return $class;
            }
        });

Then in your HTML, you would have

<div class="$index | classFilter" ng-repeat="metrics in dashboard">
 <div align="center">
  <h3>{[{metrics.value}]}</h3>
  <span class=dashboardtext>{[{metrics.name}]}</span>
 </div>
</div>

Upvotes: 0

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

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>

Upvotes: 3

Related Questions