Chapter 1: Recursive directives
by msfrisbie
HTML
<script src="https://code.angularjs.org/1.3.2/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MainCtrl">
<tree val="data"></tree>
</div>
<script type="text/ng-template" id="recursive.html">
<span>{{ val.text }}</span>
<button ng-click="deleteSubtree()">delete</button>
<ul ng-if="isParent" style="margin-left:30px">
<li ng-repeat="item in val.items">
<tree val="item" parent-data="val.items"></tree>
</li>
</ul>
</script>
</div>
JavaScript
angular.module('myApp', [])
.controller('MainCtrl',function($scope) {
$scope.data = {
text: 'Primates',
items: [
{
text: 'Anthropoidea',
items: [
{
text: 'New World Anthropoids'
},
{
text: 'Old World Anthropoids',
items: [
{
text: 'Apes',
items: [
{
text: 'Lesser Apes'
},
{
text: 'Greater Apes'
}
]
},
{
text: 'Monkeys'
}
]
}
]
},
{
text: 'Prosimii'
}
]
};
})
.directive('tree', function($compile, $templateCache) {
return {
restrict: 'E',
scope: {
val: '=',
parentData: '='
},
link: function(scope, el, attrs) {
scope.isParent = angular.isArray(scope.val.items)
scope.deleteSubtree = function() {
if(scope.parentData) {
scope.parentData.splice(
scope.parentData.indexOf(scope.val),
1
);
}
scope.val={};
}
el.replaceWith(
$compile(
$templateCache.get('recursive.html')
)(scope)
);
}
};
});