Phil Phil - 5 months ago 9
AngularJS Question

AngularJS ng-repeat an unknown deep array

I need to have the possibility to print out a possible infinite deep array-structure into a list. Here's the code from a modified AngularJS-example where I have added some more deep children in the array. How can I print

child of child
and even its children as well? Is there a way I can get it to repeat forever as long as there is more children?

HTML

<div ng-app>
<div ng-controller="TodoCtrl">
<ul>
<li ng-repeat="todo in todos">
<span>{{todo.text}}</span>
<ul>
<li ng-repeat="child in todo.children">
<span>{{child.text}}</span>
<!-- What about the next one -->
</li>
</ul>
</li>
</ul>
</div>
</div>


JS

function TodoCtrl($scope) {
$scope.todos = [{
text: 'root 1',
children: [{
text: 'child of root 1',
children: [{
text: 'child of child',
children: []
}]
}]
}, {
text: 'root 2',
children: []
}];
}


Fiddle: https://jsfiddle.net/U3pVM/25866/

Answer

You can use the view recursively this way:

<script type="text/ng-template" id="todo.html">
    <div>
        <div>{{ todo.text }}</div>
        <ul>
            <li ng-repeat="todo in todo.children" ng-include="'todo.html'"></li>
        </ul>
    </div>
</script>

<div ng-controller="MyController">
  <ul>
    <li ng-repeat="todo in todos" ng-include="'todo.html'"></li>
  </ul>
</div>

Here the DEMO based on your sample data.