jimmy
jimmy

Reputation: 4881

How to detect when all directives have loaded?

This is a spinoff of another question (Angular: running function in controller when all directives are loaded) as this one is general.

How can I detect when all angular directives on a page have loaded?

EDIT:

The only way I found so far is by setting up a directive at the highest level which triggers a scope function during it's link function. This works as angular compiles all directives on a page from outer to inner and calls link functions from inner to outer.

Downside: This no longer works if any of the inner directives uses a templateUrl as this will happen asynchronous. This will lead to the outer directives link function running before the inner directives link function. Additionally you'll have to add a directive to all views/includes.

EDIT2:

I found a great answer to a similar question which describes the problem above. And in the comments j_walker_dev mentions the following:

The way i got around this was to use template, like mentioned. 
But to inject $templateCache and do template: $templateCache.get('url.tpl.html').

SO question: How to execute parent directive before child directive?

At least with this once can continue using templateUrls as it avoids the asynchronous behavior of template loading in directives.

Upvotes: 0

Views: 1633

Answers (1)

Pierre Gayvallet
Pierre Gayvallet

Reputation: 2953

this is how protractor synchronize :

functions.waitForAngular = function(rootSelector, callback) {
  var el = document.querySelector(rootSelector);
  try {
    if (angular.getTestability) {
      angular.getTestability(el).whenStable(callback);
    } else {
      angular.element(el).injector().get('$browser').
          notifyWhenNoOutstandingRequests(callback);
    }
  } catch (e) {
    callback(e);
  }
};

Knowing that directives in cache will execute synchronously and one that needs to load template from server will execute before the $browser notify, This is how I would do it (if waiting for ajax requests others than for templates is not an issue)

Upvotes: 0

Related Questions