How to handle recursive data rendering with AngularJS

I have an application that has a dataset that has a recursive relationship (tree view using recursion.) I tried several ways to implement this using Angular, none of which are viable results.

The idea here is that I want this data to be displayed using a set of nested lists, which allows the use of multiple (7+) depth levels. To simplify things (my application uses Restangular), I built the following plunker:

http://plnkr.co/edit/dKT9OvpsMgnxmLwgF0ij

As long as the top-level data is displayed correctly (only the first header), my attempt to recursion using nested controllers seems to fail. The idea here is that each β€œchild” in the tree is rendered using its own controller, which can then display its children, and so on and so forth. I understand that nested controllers may not be the "best" way, but after a long search I did not find the "best" alternative.

It is important that the resulting solution retains the concept of nesting here (each element appears below its parent element with a slight indentation.)

+4
source share
3 answers

rather than embed controllers, embed data and just have one controller.

the view is processed by a template that recursively refers to it.

as chadermani tied, there are some answers there.

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

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

and code from the script

<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: []}]; }]); 
+12
source

If you are familiar with the batarang tool, it has a tree-like area region. Here you can see the source:

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

The idea is simple. Using the $ compilation to recursively render this directive for each child she finds until there are no more children to render.

I saw the same idea for other alternatives, look here:

Is it possible to create a tree view using Angular?

+1
source

Source: https://habr.com/ru/post/1498700/


All Articles