Reputation: 5204
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.
Upvotes: 4
Views: 509
Reputation: 5855
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>
Upvotes: 3
Reputation: 494
Try the following:
module.js
var app = angular.module('app', []);
app.component("category", {
controller: function() {
this.data = {
category_name: 'cat1',
children: [{
category_name: 'cat1-A',
children: [{
category_name: 'cat1-A-a',
children: [{
category_name: 'cat1-A-a-1',
children: []
},
{
category_name: 'cat1-A-a-2',
children: []
}
]
}]
}]
};
},
template: '<child current-cat="$ctrl.data"></child>'
});
app.component("child", {
template: '<div>{{$ctrl.currentCat.category_name}}' +
'<div style="padding-left:20px;" ng-repeat="cat in $ctrl.currentCat.children">' +
'<child current-cat="cat"></child>' +
'</div>' +
'</div>',
bindings: {
currentCat: '<'
}
});
index.html
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
<script src="module.js"></script>
</head>
<body ng-app="app">
<div>
<category></category>
</div>
</body>
</html>
Upvotes: 0