I'm looking to display data in a tree structure in a web app. I was hoping to use Angular for this task.
Looks like ng-repeat will allow me to iterate through a list of nodes, but how can I then do nesting when a given node's depth increases?
I tried the following code, but the auto-escaping of the HTML is preventing this from working. Plus, the end ul tag is in the wrong place.
I'm pretty sure that I'm going about this problem entirely the wrong way.
Any ideas?
When making something like this the best solution is an recursive directive. However, when you make such an directive you find out that AngularJS gets into an endless loop.
The solution for this is to let the directive remove the element during the compile event, and manually compile and add them in the link events.
I found out about this in this thread, and abstracted this functionality into a service.
With this service you can easily make a tree directive (or other recursive directives). Here is an example of an tree directive:
See this Plunker for a demo. I like this solution best because:
Update: Added support for a custom linking functions.
You can use angular-recursion-injector for that: https://github.com/knyga/angular-recursion-injector
Allows you to do unlimited depth nesting with conditioning. Does recompilation only if needed and compiles only right elements. No magic in code.
One of the things that allows it to work faster and simpler then the other solutions is "--recursion" suffix.
Another example based off the original source, with a sample tree structure already in place (easier to see how it works IMO) and a filter to search the tree:
JSFiddle
Based on @ganaraj 's answer, and @dnc253 's answer, I just made a simple "directive" for the tree structure having selecting, adding, deleting, and editing feature.
Jsfiddle: http://jsfiddle.net/yoshiokatsuneo/9dzsms7y/
HTML:
JavaScript:
If you are using Bootstrap CSS...
I have created a simple re-usable tree control (directive) for AngularJS based on a Bootstrap "nav" list. I added extra indentation, icons, and animation. HTML attributes are used for configuration.
It does not use recursion.
I called it angular-bootstrap-nav-tree ( catchy name, don't you think? )
There is an example here, and the source is here.
When the tree structure is large, Angular (up to 1.4.x) becomes very slow at rendering a recursive template. After trying a number of these suggestions, I ended up creating a simple HTML string and using
ng-bind-html
to display it. Of course, this is not the way to use Angular featuresA bare-bones recursive function is shown here (with minimal HTML):
In the template, it only needs this one line:
This bypasses all of Angular's data binding and simply displays the HTML in a fraction of the time of the recursive template methods.
With a menu structure like this (a partial file tree of a Linux file system):
The output becomes: