Reputation: 4430
I'm having trouble with a nested list Directive using Angular. Each time I try to run my code the browser crashes when I call the directive recursively.
I'd like to output a new list item if the children
property in the data has items in it.
Here's a fiddle to my code, I removed the directives call to itself so that it does not crash the browser. http://jsfiddle.net/8p3bf4ec/
JS:
var jsonData = {
"title": "Home",
"author": "Mary",
"children": [
{
"title": "Clothing",
"author": "Robert",
"children": [
{
"title": "Shirts",
"author": "Bill",
"children": []
}
]
},
{
"name": "Electronics",
"author": "William",
"children": []
}
]
};
angular.module('myApp', []);
angular.module('myApp').directive('itemList', function() {
return {
scope: true,
templateUrl: 'itemListTemplate.html',
controller: function($scope) {
$scope.nodes = jsonData;
console.log($scope.nodes);
}
};
});
Template:
<div ng-app="myApp">
<item-list></item-list>
<script type="text/ng-template" id="itemListTemplate.html">
<ul>
<li ng-repeat="node in nodes">
{{node.title}}
</li>
</ul>
<!-- Removed this because it makes the browser crash
<item-list></item-list>
-->
</script>
</div>
Upvotes: 0
Views: 600
Reputation: 139
It is because you infinitely iterate through jsonData instead of each node's children. I guess you should not use directive here at all because there is not much logic and it adds unnecessary complexity. Just use ng-include instead of directive. Something like this:
<script type="text/ng-template" id="tree-view">
<ul>
<li ng-repeat="item in items">
<!-- any data you want to display from item itself -->
<div
ng-if="item.children && item.children.length"
ng-init="items=item.children"
ng-include="'tree-view'">
</div>
</li>
</ul>
</script>
<div class="tree-view" ng-include="'tree-view'"></div>
Upvotes: 1