I have an object containing infinitely nested data, like the following example:
[
{
name: "Foo",
value: "Bar",
sub: [
{
name: "ABC",
value: "LLL",
sub: [
...
]
},
{
...
}
]
},
{
name: "Oof",
value: "Rab"
sub: [
...
]
}
]
Every element can contain a sub
value, which would contain one or multiple elements with the same structure (name
, value
, sub
if there are more sub-elements).
Now, I know how to do a ng-repeat
, but with a single ng-repeat
, I'll get only the elements from the first level. If I did a second ng-repeat
inside the first one, I'd get only the items from the second level, etc...
As I don't know how many levels there would be, I can't just nest a few ng-repeat
inside each other. That is why I'm looking for a way to recursively loop over the entire data array and represent all the items that are inside, inside an Angular directive (that is, using Angular's directives/attributes inside my HTML code). Is that possible with Angular (1.3.x) ?
I have an object containing infinitely nested data, like the following example:
[
{
name: "Foo",
value: "Bar",
sub: [
{
name: "ABC",
value: "LLL",
sub: [
...
]
},
{
...
}
]
},
{
name: "Oof",
value: "Rab"
sub: [
...
]
}
]
Every element can contain a sub
value, which would contain one or multiple elements with the same structure (name
, value
, sub
if there are more sub-elements).
Now, I know how to do a ng-repeat
, but with a single ng-repeat
, I'll get only the elements from the first level. If I did a second ng-repeat
inside the first one, I'd get only the items from the second level, etc...
As I don't know how many levels there would be, I can't just nest a few ng-repeat
inside each other. That is why I'm looking for a way to recursively loop over the entire data array and represent all the items that are inside, inside an Angular directive (that is, using Angular's directives/attributes inside my HTML code). Is that possible with Angular (1.3.x) ?
1 Answer
Reset to default 12Yes, it is possible by using inline template
Example :
<script type="text/ng-template" id="namVal">
{{ item.name}}
<ul ng-if="item.sub">
<li ng-repeat="item in item.sub" ng-include="'namVal'"></li>
</ul>
</script>
in html
<ul>
<li ng-repeat="item in items" ng-include="'namVal'"></li>
</ul>
UPDATED using Plunkr example by @alexandernst http://plnkr.co/edit/dKlrvtYH1IbQXFUEk2Wx?p=preview