Reputation: 1557
I have a dictionary in my controller:
thing = {
key1 = value1,
key2 = value2,
...
keyN = valueN,
};
I am using ng-repeat to iterate through it like so: ng-repeat="(key, value) in thing"
But I want to iterate through multiple values at a time, such that for each iteration, I can use key1: value1
and key2: value2
, then the next I can use key3: value3
, key4: value4
etc...
Is there a way to iterate through with ng-repeat, iterating more than one item at a time? Thanks.
Upvotes: 1
Views: 2184
Reputation: 1633
I suggest to create a filter:
app.filter('coupledItems', function(){
return function(items){
var isEven = false;
var coupledItems = [];
var temp = {};
angular.forEach(items, function(item){
if(isEven){
temp['item2'] = item;
coupledItems.push(temp);
temp = {};
}
else{
temp['item1'] = item;
}
isEven = !isEven;
});
if(temp['item1']){ // If odd, put it to last item
coupledItems.push(temp)
}
return coupledItems;
}
});
When use it:
<tr ng-repeat="item in items | coupledItems">
<td>{{item.item1.key}}</td>
<td>{{item.item2.key}}</td>
</tr>
Upvotes: 0
Reputation: 7201
Not without changing your model's structure or using additional structure. What I mean by the latter is, you could create an array with key names, like this:
$scope.doubled = [['key1', 'key2'], ['key3', 'key4'], ... ];
And then the iteration is quite straightforward, e.g.:
<div ng-repeat="keys in doubled">
<div ng-repeat="key in keys">
{{ thing[key] }}
</div>
</div>
It is also a more reliable way of iterating in a predictible manner, because you should mind that while iterating over the object's properties, you cannot (or at least shouldn't) rely on a specific order of those properties (see https://github.com/angular/angular.js/issues/6210).
Upvotes: 2
Reputation: 119
Yes. Example:
ng-repeat="t in thing"
{{ t[$index] + t[$index+1] }}
Upvotes: -1