Pranjal
Pranjal

Reputation: 796

Call function after angular all directives are loaded

I have multiple custom directives in my ngApp. The demo code is:

<top-nav></top-nav>
<left-sidebar></left-sidebar>
<div class="content">
    ....
</div>

The height of the 'left-sidebar' needs to be adjusted according to the height of the 'top-nav'. Similarly there are other interdependent UI tasks. I want to run the post-load code (say app.initializeUI();) only after ALL the directives have been loaded and rendered.

Now, How do I achieve that?

EDIT :

Currently I am using the following code :

App.run(function($timeout){
    $timeout(function(){ app.init() },0);
    });

This runs fine, however, I am not sure this is the perfect way of doing this.

EDIT 2:

For people who want to avoid setting styles in js - use CSS Flexbox. I find it much better than calculating heights post page load. I got a good understanding of flexbox here

Upvotes: 2

Views: 867

Answers (1)

Michael Kang
Michael Kang

Reputation: 52837

I would create an attribute directive with isolated scope, set terminal=true and add it to your body tag. Then in your link function, setup a $watch - isInitialized which is initially false. In your $watch handler, call your app.init(), and then de-register the $watch, so that it is always initialized once.

Setting up a terminal directive has consequences - no other directive can run after the terminal directive on the same element. Make sure this is what you want. An alternative is to give your directive the lowest possible value so that it is compiled first, and linked last.

The important pieces to this solution are:

  1. By adding your Directive to the body tag, you ensure that it is linked last.
  2. By adding a $watch, you ensure that all other directives have gone through a digest cycle, so by the time your $watch handler is called, all other directives should have already rendered.

Note of caution: The digest cycle may run several times before scope changes stabalise. The above solution only runs after the first cycle, which may not be what you want if you really want the final rendering.

Upvotes: 1

Related Questions