Reputation: 11
I am want to make a ng-repeat in a ng-repeat and show the results of the second ng-repeat after every 3 item of the first ng-repeat. When the second ng-repeat is out of data I want to start it from the start again until the first ng-repeat is done.
Arrays:
items = [
"Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8", "Item9", "Item10"
]
bars = [
"BAR1", "BAR2"
]
I want my output to be:
Upvotes: 1
Views: 1417
Reputation: 163
If you want something purely template based:
<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>
Demo: http://jsfiddle.net/SHjy9/26/
Upvotes: 2
Reputation: 101700
It'll most likely be simpler if you build up the list of items before iterating over them in ng-repeat, like this:
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>
Upvotes: 0
Reputation: 2138
One solution would be to create a new array and insert your bars
elements every 3rd index :
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);
});
Then you can ng-repeat
on newArray
.
Upvotes: 0