2
<table>    
<tr ng-repeat="customer in myData"
        ng-if="$even" style="background-color: gray">
        <td>{{$index+1}}</td>
        <td>{{customer.name}}</td>
        <td>{{customer.city}}</td>
    </tr>
</table>

I got the data from a JSON file and display in view.I need a specific color for even/odd row using angularJS directive. Please help me. Advance thanks.

Srikrushna
  • 4,366
  • 2
  • 39
  • 46

3 Answers3

1

You could track by $index and determine if the row is odd or even, then set the style based off a ternary operator using the ngStyle style directive.

However, I would recommend using the ngClass directive which would give you better separation between markup and styles, and also make the DOM cleaner.

As an example:

<li ng-repeat="item in tc.list track by $index" ng-class="$index % 2 == 0 ? 'even' : 'odd'">{{item}}</li>

Full Snippet:

  var app = angular.module("TestApp",[]);
  app.controller("TestController", function() {
      var vm = this;
      vm.list = [];
      
      function populateDummyItems() {
        vm.list.push("One");
        vm.list.push("Two");
        vm.list.push("Three");
        vm.list.push("Four");
      }
      
      populateDummyItems();
      
  });
  .even {
    background-color: lightblue;
  }
  
  .odd {
    background-color: yellow;
  }
  
  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

  <body ng-app="TestApp">
    <h1>Darren's test application!</h1>
    <ul ng-controller="TestController as tc">
      <li ng-repeat="item in tc.list track by $index" ng-class="$index % 2 == 0 ? 'even' : 'odd'">{{item}}</li>
    </ul>
  </body>

External Plunker:

https://plnkr.co/edit/4LSB0oKYr0VgSQj0jTxP?p=preview

Darren
  • 68,902
  • 24
  • 138
  • 144
1

If you don't want to use css, you can try ng-style

<table>    
  <tr ng-repeat="customer in myData" ng-style="{'background-color':$even?evenColor:oddColor}">
    <td>{{$index+1}}</td>
    <td>{{customer.name}}</td>
    <td>{{customer.city}}</td>
  </tr>
</table>

js

$scope.evenColor = 'yellow'; // you can also enter the hex '#ffff00' here
$scope.oddColor = 'red';
amansinghgusain
  • 764
  • 5
  • 17
0

If you don't want to use Stylesheets, you can use the angular ngStyle attribute

https://docs.angularjs.org/api/ng/directive/ngStyle

example:

HTML:

<div ng-app="OddEven">
    <ul ng-controller="oddEvenController">
        <li ng-repeat="item in list" ng-style="$index % 2 == 0 ? {'color':'blue'} : {color:'red'}">{{item}}</li>
    </ul>
</div>

JS:

var angularApp = angular.module("OddEven",[]);
angularApp.controller("oddEvenController", function($scope) {
    $scope.list = ["a", "b", "c", "d", "e", "f"];
});

If you can use Stylesheets, look at the accepted answer of

How to assign alternate class to rows in Angular JS?

Community
  • 1
  • 1
Parag
  • 400
  • 1
  • 3
  • 11