Skip to content

AngularJS: A lazily-loaded recursive tree widget

2013 August 19
by Alec

Note (July 2014): I can no longer recommend this directive as there are far better tree directives out there. As always, YMMV.

Original post:
I had the chance to use the wonderful AngularJS javascript framework for another project, so I jumped on it. One requirement was a tree representation of some data, where children could be loaded dynamically. A quick google search revealed a dearth of tree widgets, so I hacked something together myself. Inspiration came from Andy Joslin’s recursive tree implementation.

Often, a dataset is too large to be efficiently preloaded on the client-side, so it makes sense to lazily load a node’s children on demand. In this implementation, the loading function can either return a promise or an array of child nodes.


  • Node selection. Catch a “nodeSelected” event on the controller’s scope. You can also pass an ID for the node which should be initially selected.
  • Dynamic loading of children. Define a function that will be called with the node that is being expanded.
  • Auto-expansion. Define a comma-separated hierarchy of node ids to expand.

This is a very rough implementation, surely replete with bugs, but has functioned thus far for my uses. Usage, suggestions and forks are all welcomed. Try it out:

Edit (2/28/14): Finally posted the source code to GitHub. I should also mention that of all the modules I’ve open-sourced, this is by far the least-tested. It is the only one not to have seen extensive production use.

5 Responses
  1. February 7, 2014


    Thank you very much for this very cool source code.
    I have tweak little bit your code to pull the data from a json source via $http service.

    I have shared the source code here:


    • Alec permalink*
      February 7, 2014


      A common use case! I will have to put the source on GitHub to make such forks easier..

  2. bigdog permalink
    April 16, 2014

    hi, i wanna use your plugin to my project, async fetch tree nodes, i add a http.get() in addChildren function, but it’s not worked, can you show me some demo code , thank you very much….

  3. Jmd permalink
    July 8, 2014

    Personally I feel these things can be done far more simple in angular than building gigantic directives, see:

    • Alec permalink*
      July 8, 2014

      Agreed. Of all the code I’ve posted on this site, this tree has seen the least amount of refinement. I will not be supporting it and am recommending other solutions. Thanks for the feedback.

Comments are closed.