0

在我的 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 应该根据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>
4

1 回答 1

1

您可以使用它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>

于 2016-09-16T11:21:34.123 回答