在ng-repeat中使用ng-if的$index。

4

我有一个这样的数组,其中包含动物和水果列表,但顺序是随机的。

 $scope.items = [{name:'mango',type:'fruit'},{name:'cat',type:'animal'},{name:'dog',type:'animal'},{name:'monkey',type:'animal'},{name:'orange',type:'fruit'},{name:'banana',type:'fruit'},...]

然后我有一个颜色数组,如下:

$scope.colorSeries = ['#3366cc', '#dc3912', '#ff9900',...];

$scope.setBGColor = function (index) {
   return { background: $scope.colorSeries[index] }
}

我正在使用items数组,仅在具有背景颜色的div中呈现水果,该颜色是基于索引从colorSeries中选择的,例如colorSeries[0]将给我 #3366cc。
<div data-ng-repeat="item in items " ng-if="item.type =='fruit'">
   <label ng-style="setBGColor($index)">{{item.name}}</label>
</div>

如果items数组的长度小于colorSeries数组的长度,则一切正常。问题出现在当colorSeries数组的长度小于items数组的长度时,例如我有一个由3种颜色组成的color series,那么对于这个items数组,最后一项即橙色需要一个索引为colorSeries[4]的颜色,而我只渲染了三个项,所以该索引是未定义的(undefined)。因此,是否可能获取像0、1、2这样的索引,即使用ng-if渲染元素时的索引。


那么,你想要的不是colorSeries [4],你尝试编写什么逻辑来选择从colorSeries中的项目? - Lee Willis
我希望得到colorSeries[2],因为我只有三个水果类型的元素。 - user3603255
请花些时间审查答案并选择正确的答案(或添加您自己的解决方案,如果不同)。 - domokun
3个回答

3

不要使用ng-if,我建议使用过滤器。这样,$index将始终与在应用过滤器后的结果列表中的索引相对应。

<div data-ng-repeat="item in items|filterFruit">
   <label ng-style="setBGColor($index)">{{item.name}}</label>
</div>

angular.module('app.filters', []).filter('filterFruit', [function () {
    return function (fruits) {
        var i;
        var tempfruits = [];
        var thefruit;

        if (angular.isDefined(fruits) && 
            fruits.length > 0) {
                for(thefruit = fruits[i=0]; i<fruits.length; thefruit=fruits[++i]) {
                   if(thefruit.type =='fruit') 
                      tempfruits.push(thefruit);
                }
        }
        return tempfruits;
    };
}]);

0

试试这个...

 this.itemList = [{
        name:'apple'
    }, {
        name: 'fruit'
    }];

    this.colorlist = [{ color: 'red' }, { color: 'orange' }, { color: 'blue' }];

  <div data-ng-repeat="item in itemList " ng-if="item.name=='fruit'">
  <label ng-style="colorlist [$index]">{{item.name}}</label>
  </div>

0
如果我是你,我会将颜色嵌入到$scope.items对象中,因为你总是与水果一起使用它们。
无论如何,针对你特定的代码配置,我会在我的控制器中添加一个计数器,并使用它来循环遍历颜色。像这样:
app.controller('myCtrl', function ($scope) {

  $scope.colorSeries = ['#3366cc', '#dc3912', '#ff9900',...];

  var colorCounter = $scope.colorSeries.length;
  var colorIdx = -1;
  $scope.setBGColor = function () {
    // get back to the first color if you finished the loop
    colorIdx = colorCounter? 0: colorIdx+1

    return { background: $scope.colorSeries[colorIdx] }
  }

})

然后在您的视图中(请注意,没有$index

<div data-ng-repeat="item in items " ng-if="item.type =='fruit'">
   <label ng-style="setBGColor()">{{item.name}}</label>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接