具有间隔和循环的ng-repeat中的Ng重复

时间:2016-03-18 14:01:46

标签: angularjs ng-repeat

我想在ng-repeat中进行ng-repeat,并在第一次ng-repeat的每3项后显示第二次ng-repeat的结果。当第二次ng-repeat没有数据时,我想从头再次开始,直到第一次ng-repeat完成。

阵列:



items = [
  "Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9", "Item10"
]
bars = [
  "BAR1", "BAR2"
]




我希望我的输出为:

  • 第1项
  • Item2
  • 项目3
  • BAR1
  • 项目4
  • Item5
  • 项6
  • BAR2
  • Item7
  • Item8
  • Item9
  • BAR1
  • Item10

3 个答案:

答案 0 :(得分:2)

如果你想要纯粹基于模板的东西:

<div ng-repeat="item in items">
    <div>{{item}}</div>
    <div ng-if="($index+1) % 3 === 0">{{bars[ (($index+1) / 3 - 1)%(bars.length) ]}}</div>
</div>

演示:http://jsfiddle.net/SHjy9/26/

答案 1 :(得分:0)

一种解决方案是创建一个新数组并在每个第三个索引处插入bars个元素:

var newArray = [];

items.forEach(function (item, index) {
    if (index % 3 === 0) {
       // bars.shift() will remove the first element of bars and return it
       newArray.push(bars.shift());
    }

    newArray.push(item);
});

然后您可以在ng-repeatnewArray

答案 2 :(得分:0)

如果你在ng-repeat中迭代它们之前建立项目列表,那么它很可能会更简单,如下所示:

&#13;
&#13;
var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', ['$scope', function ($scope) {
  $scope.items = [
    "Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9", "Item10"
  ];

  $scope.bars = [
    "BAR1", "BAR2"
  ];

  $scope.allItems = function () {
    var arr = [], j = 0;
    $scope.items.forEach(function (item, idx) {
      if (idx > 0 && idx % 3 === 0){
        arr.push($scope.bars[j % $scope.bars.length]);
        j += 1;
      }
      arr.push(item);
    });
    return arr;
  };

}]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <ul>
    <li ng-repeat="item in allItems() track by $index">
      {{ item }}
    </li>
  </ul>
</div>
&#13;
&#13;
&#13;