var app = angular.module("MyApp", []); app.controller("MyCtrl", function($scope){ $scope.data = { value: "1", children: [ { value: "1-1", children: [ { value: "1-1-1", children: [] } ] }, { value: "1-2", children: [] } ] }; }); app.directive("mytree", function($compile){ var template = '' + '<div class="node">' + ' <div class="value">{{node.value}}</div>' + ' <mytree ng-repeat="child in node.children" node="child" />' + '</div>'; return { restrict: "E", scope: { node: "=" }, template: template, // http://stackoverflow.com/questions/19125551/angularjs-understanding-a-recursive-directive compile: function(tElement, tAttr, transclude) { var contents = tElement.contents().remove(); var compiledContents; return function(scope, iElement, iAttr) { if(!compiledContents) { compiledContents = $compile(contents, transclude); } compiledContents(scope, function(clone, scope) { iElement.append(clone); }); }; } }; });
<div ng-app="MyApp" ng-controller="MyCtrl"> <mytree node="data" /> </div>
.node{ margin-left: 1em; } .value{ font-size: 24px; }