Reputation: 5648
I often find myself in the situation where I need an ng-repeat on something that should correspond to nothing in the DOM. For example, say I have the following object:
groupedHeaders = {
'group1' : ['header1', 'header2'],
'group2' : ['header3', 'header4', 'header5'],
'group3' : [.....],
...,
...,
'groupN' : [....]
}
I want to create a table with all of the headers. So I want to do something like this to give me one row with one th element per header:
<tr>
<dummy ng-repeat="(group, headers) in groupedHeaders">
<th nr-repeat="header in headers">
{{header}}
</th>
</dummy>
</tr>
So the "dummy" element just adds another "level" to my iteration (like having two for loops).
Is there any way to have an ng-repeat on an element which doesn't correspond to anything in the DOM?
If not, am I missing something basic about how to do this? I am using Angular 1.2.
Upvotes: 0
Views: 1928
Reputation: 18546
The only solution seems to be a "dummy" element within the DOM without any logic.
If you prefix the tag with "data-", it is even HTML5 compatible.
<tr>
<data-ng-repeat-dummy ng-repeat="(group, headers) in groupedHeaders">
<th nr-repeat="header in headers">
{{header}}
</th>
</data-ng-repeat-dummy>
</tr>
Obviously you could also create a very empty directive that does nothing, basically creating the same code. (with ng-transclude)
<data-ng-repeat-dummy ng-repeat="(group, headers) in groupedHeaders" ng-transclude>
angular.module('mymodule', []).directive('dataNgRepeatDummy', [function () {
return {
restrict: 'E',
scope: {},
transclude: true
};
}]);
If you add "replace:true" to the directive, you might even get it completely out of your DOM. However, replace:true is deprecated: Why is replace deprecated in AngularJS?
Alternatively, you could flatten your data in the controller if thats applicable.
Upvotes: 1