angularjs 仅为整个集合中的可见对象替换颜色

angularjs alternate colouring only for the visible objects in the entire set

在我的 angularjs 应用程序中,我有以下 json。

   $scope.itemsList = {
       "busName": "ABC",
       "needsToHide": true,
       "num": 123

   }, {
       "busName": "xyz",
       "needsToHide": false,
       "num": 567
   }, {
       "busName": "pqr",
       "needsToHide": true,
       "num": 654
   }, {
       "busName": "lmn",
       "needsToHide": false,
       "num": 672
   }

在我的 html 中,我有简单的 ng-repeat :

<label ng-repeat="eachPosition itemsList track by eachPosition.num" ng-show="!eachPosition.needsToHide">
  <span> {{eachPosition.busName}} </span>                               
</label>

现在我需要使用 ng-class 将替代颜色仅应用于可见标签。我的意思是在给定的列表中只有 "xyz" 和 "lmn" 在屏幕上可见,并且应该为它们提供其他颜色。

如何应用 ng-class="{even: !($index%2), odd: ($index%2)}",在这种情况下仅适用于可见标签,类似于下面的 html,但是 html 应该添加偶数或奇数 class es 是否正确地基于 needsToHide 标志?

<label ng-repeat="eachPosition itemsList track by eachPosition.num" ng-show="!eachPosition.needsToHide" ng-class="{even: !($index%2), odd: ($index%2)}">
      <span> {{eachPosition.busName}} </span>                               
    </label>

您可以使用 filter 来执行此操作。

示例 jsfiddle

angular.module('ExampleApp', [])
  .controller('ExampleController', function() {
    var vm = this;
    vm.itemsList = [{
      "busName": "ABC",
      "needsToHide": true,
      "num": 123

    }, {
      "busName": "xyz",
      "needsToHide": false,
      "num": 567
    }, {
      "busName": "pqr",
      "needsToHide": true,
      "num": 654
    }, {
      "busName": "lmn",
      "needsToHide": false,
      "num": 672
    }];
  });
.even {
  color: red;
}
.odd {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="ExampleController as vm">
    <div>With <code>ng-class</code> and <code>$even,$odd</code> property. </div>
    <label ng-repeat="eachPosition in vm.itemsList|filter:{needsToHide:false} track by eachPosition.num" ng-class="{even: $even, odd: $odd}">
      <span> {{eachPosition.busName}} </span>
    </label>
    <div>With <code>ng-class</code> and <code>$index</code> property. </div>
    <label ng-repeat="eachPosition in vm.itemsList|filter:{needsToHide:false} track by eachPosition.num" ng-class="{even: !($index%2), odd: ($index%2)}">
      <span> {{eachPosition.busName}} </span>
    </label>
    <div>With <code>ng-style</code> and <code>$even,$odd</code> property. </div>
    <label ng-repeat="eachPosition in vm.itemsList|filter:{needsToHide:false} track by eachPosition.num" ng-style="{color: $even?'red':'green'}">
      <span> {{eachPosition.busName}} </span>
    </label>
  </div>
</div>