使用angularJS指令no CSS

时间:2017-03-04 12:51:15

标签: angularjs

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

我从JSON文件中获取数据并在视图中显示。我需要使用angularJS指令为偶数/奇数行指定特定颜色。请帮我。提前谢谢。

3 个答案:

答案 0 :(得分:1)

您可以按$index跟踪并确定该行是奇数还是偶数,然后使用ngStyle样式指令设置基于ternary运算符的样式。

但是,我建议使用ngClass指令,这样可以更好地区分标记和样式,并使DOM更清晰。

举个例子:

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

完整代码段

  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>

外部暴徒:

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

答案 1 :(得分:1)

如果您不想使用css,可以尝试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';

答案 2 :(得分:0)

如果您不想使用样式表,可以使用角度ngStyle属性

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

示例:

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"];
});

如果您可以使用样式表,请查看

的接受答案

How to assign alternate class to rows in Angular JS?