How to handle recursive rendering of data using AngularJS How to handle recursive rendering of data using AngularJS angularjs angularjs

How to handle recursive rendering of data using AngularJS


rather than nest your controllers, nest the data and just have the one controller.

the view is handled by a template that references itself recursively.

as chadermani has linked to, there are some answers out there.

here is a fiddle with a great example (not my code)

http://jsfiddle.net/brendanowen/uXbn6/8/

and the code from the fiddle

<script type="text/ng-template"  id="tree_item_renderer.html">    {{data.name}}    <button ng-click="add(data)">Add node</button>    <button ng-click="delete(data)" ng-show="data.nodes.length > 0">Delete nodes</button>    <ul>        <li ng-repeat="data in data.nodes" ng-include="'tree_item_renderer.html'"></li>    </ul></script><ul ng-app="Application" ng-controller="TreeController">    <li ng-repeat="data in tree" ng-include="'tree_item_renderer.html'"></li></ul>angular.module("myApp", []).controller("TreeController", ['$scope', function($scope) {    $scope.delete = function(data) {        data.nodes = [];    };    $scope.add = function(data) {        var post = data.nodes.length + 1;        var newName = data.name + '-' + post;        data.nodes.push({name: newName,nodes: []});    };    $scope.tree = [{name: "Node", nodes: []}];}]);


If you are familiarized with batarang tool, it has a treeview of scopes. You can see the source here:

https://github.com/angular/angularjs-batarang/blob/master/js/directives/scopeTree.js

The idea is simple. Using $compile to recursively render that directive for every children it finds until there is no more children to render.

I saw that same idea for other alternatives, take a look here:

Is it possible to make a Tree View with Angular?