2016-03-18 67 views
0

我想在ng-repeat中做一個ng-repeat並在第一個ng-repeat的每3個項目後顯示第二個ng-repeat的結果。當第二個ng-repeat超出數據範圍時,我想再次從頭開始,直到第一個ng-repeat完成。ng-重複的間隔和循環ng-repeat

陣列:

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

我希望我的輸出是:

  • 項目1
  • 項目2
  • 項目3
  • BAR1
  • 項目4
  • 項目5
  • 項6
  • BAR2
  • Item7
  • Item8
  • Item9
  • BAR1
  • Item10

回答

0

ö NE的解決方案是創建一個新的陣列並插入您bars元素每3個指標:

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

0

,如果你遍歷他們NG重複,如在此之前建立的項目列表這將最有可能是簡單的:

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

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

1

如果你想要的東西純粹模板基於:

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

+0

這是我需要的。非常感謝你。 – user2764621