Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Recursive ng-include - How to know when entire tree is rendered

I'm trying to render a hierarchical tree recursively using ng-include. Here is a fiddle

The problem is in my link function gets called before the rendering is done to try to initialize a menu plugin on an empty list.

link: function (scope, element, attrs) {

    var $menus = element.find("ul");

    //Prints empty element        
    console.log($menus.html());

    //No real $menus to initialize 
    //$menus.menuAim({ });

}

I know there is onload on ng-include, but I don't want to resort to some ugly hack like incrementing a counter on each onload and comparing against count of elements, as calculating the count gets tricky due to the hierarchy structure.

What's a cleaner way to know when the ng-include has finished a full recursive rendering and all elements are on the page?

I tried using postLink instead of link but directive still prints an empty <ul>:

link: {
     pre: angular.noop,
     post: function(scope, element, attrs){
          //no difference
     }
}
like image 828
parliament Avatar asked Mar 05 '14 18:03

parliament


1 Answers

You could use a $timeout for the above purpose. If the second parameter i.e., "delay" is not provided, the default behaviour is that it executes the function after the completion of dom rendering. So the code would be like:

    $timeout(function () {
        //Prints empty element        
        console.log($menu.html());
    });

And $timeout needs to be injected as a dependency in the directive as

    .directive('menuHierarchy', function ($timeout) {
        //directive code
    });

In your example, it prints all the "li" nodes properly as you need it.

like image 176
swathis Avatar answered Oct 10 '22 12:10

swathis