recursive directive
using $compile to create a recursive directive
by bodine30
HTML
<div ng-app="myapp">
<div ng-controller="TreeCtrl as app">
<hub data-model="app.dataModel" children="children">
<p>{{ model.name }}</p>
</hub>
</div>
</div>
CSS
hub {
margin-left: 20px;
display: block;
}
JavaScript
var module = angular.module('myapp', []);
module.controller("TreeCtrl", function ($scope) {
this.dataModel = {
name: "Parent",
children: [{
name: "Child1",
children: [{
name: "Grandchild1",
children: []
}, {
name: "Grandchild2",
children: []
}, {
name: "Grandchild3",
children: [{
name: "GreatGrandchild1",
children: []
}, {
name: "GreatGrandchild2",
children: []
}]
}]
}, {
name: "Child2",
children: []
}]
};
});
module.directive("hub", function ($compile) {
return {
restrict: "E",
//We are stating here the HTML in the element the directive is applied to is going to be given to
//the template with a ng-transclude directive to be compiled when processing the directive
transclude: true,
scope: {
model: '=',
children: '@'
},
template:
'<ul>' +
//Here we have one of the ng-transclude directives that will be give the HTML in the
//element the directive is applied to
'<li ng-transclude></li>' +
'<li ng-repeat="child in model[children]">' +
//Here is another ng-transclude directive which will be given the same transclude HTML as
//above instance
//Notice that there is also another directive, 'tree', which is same type of directive this
//template belongs to. So the directive in the template will handle the ng-transclude
//applied to the div as the transclude for the recursive compile call to the tree
//directive. The recursion will end when the ng-repeat above has no children to
//walkthrough. In other words, when we hit a leaf.
'<hub...