I am writting an Angular plugin that will initialize an angular app module if there are none found, but if there is an already running or declared ng-app, my app will use that module instead. Ideally my code would look like the following:
// return array of apps, whether from ng-app or manually bootstrap
runningAppModules = angular.getNgApps();
if( !isEmpty(runningAppModules) )
{
var app = runningAppModules[0];
// Do something with the already initialized app like register controllers
// Or add directives
}
else
{
// manually bootstrap apps
}
I am writting an Angular plugin that will initialize an angular app module if there are none found, but if there is an already running or declared ng-app, my app will use that module instead. Ideally my code would look like the following:
// return array of apps, whether from ng-app or manually bootstrap
runningAppModules = angular.getNgApps();
if( !isEmpty(runningAppModules) )
{
var app = runningAppModules[0];
// Do something with the already initialized app like register controllers
// Or add directives
}
else
{
// manually bootstrap apps
}
Share
Improve this question
asked Jan 27, 2014 at 0:39
Dr.KnowitallDr.Knowitall
10.5k24 gold badges87 silver badges136 bronze badges
1 Answer
Reset to default 7 try {
angular.module('module-name-here');
}
catch(e) {
//not loaded
}
The module()
function will throw an error if you call it for a module that doesn't exist, unless of course you're creating one with angular.module('some-name', []);
. So, you can just wrap it in a try/catch
block to check whether or not a module is loaded.
Live demo (click).
var appElems = document.querySelectorAll('[ng-app]');
for (var i=0; i<appElems.length; ++i) {
var appName = appElems[i].getAttribute('ng-app');
try {
angular.module(appName);
}
catch(e) {
console.log('Module "'+appName+'" not loaded!');
//create the app
angular.module(appName, []);
}
}