I need to repeat over a deeply nested javascript object in my angular template. The problem is that I have no control over how the data is handed to me, and no way of knowing how deeply nested the data will be.
The data looks like this
{
category_name: 'cat1'
children: [
{
category_name: 'cat1a',
children: [...]
}
]
}
And the template
<div ng-repeat="cat in categories">
<div ng-repeat="subcat in cat.children">
{{subcat.name}}
<!--
would like to programatically place an ng-repeat here too
if subcat.children.length > 0
-->
</div>
{{cat.name}}
</div>
This checks two levels deep, but how can I recursively repeat until there are no children left? I'm thinking I need to create a custom directive that compiles a new ng-repeat as required, I'm just not sure how to go about it.
You can use ng-include with a directive script type ng-template/text and call it recursively to write n children. (PLUNKER)
<body ng-controller="MainCtrl as vm">
<script type="text/ng-template" id="nested.html">
{{item.category_name}}
<ul>
<li ng-repeat="item in item.children" ng-include="'nested.html'"></li>
</ul>
</script>
<ul>
<li ng-repeat="item in vm.data" ng-include="'nested.html'"></li>
</ul>
</body>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With