joescii
joescii

Reputation: 6533

How can I detect if an Angular app has been initialized from outside Angular?

While developing the lift-ng plugin, I have noticed an issue where sometimes the server sends events via comet to the client prior to angular initialization. This causes events to be silently missed by the application. I would like to know if there is a way to detect if an app has been initialized, i.e. all controllers, services, directives, etc have been instantiated and hence all listeners are ready for events. Because this is a plugin, I need to be able to do it without requiring the angular components to implement any code. I can add a controller, service, or whatever to the app, but the solution cannot require that every component sends an event, for instance.

Upvotes: 3

Views: 5466

Answers (1)

Mosho
Mosho

Reputation: 7078

Try something like this:

try {
    angular.bootstrap(document)
} 
catch(e) {
    console.log(!!e.message.indexOf('btstrpd')) 
    //will log true if the error is of the type `btstrpd`, 
    //you can do whatever you want with it here.
}

If there is already an app bootstrapped, angular.bootstrap will emit an error. btstrpd is the name of the error that means an app has already been bootstrapped.

This is simple enough, and I hope it works for your case, but if it doesn't ping me and I'll think of something more elaborate.


Another approach:

If you have some information about the modules, you can check the components have been bootstrapped using this:

angular.element(document.querySelector('[ng-app]')).injector().has('$http')

This finds where the ng-app attribute was used, then calls the initialized injector instance, from which you can call has to see what providers have been initialized.


Yet another approach:

Instead of angular.bootstrap you can try angular.module without a second argument, which should retrieve the module if it has been loaded or emit an error.

try {
    angular.module('moduleName')
} 
catch(e) {
    console.log(!!e.message.indexOf('nomod')) 
    //will log true if the error is of the type `nomod`, 
    //you can do whatever you want with it here.
}

Upvotes: 5

Related Questions