Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to check if an Angular app already has running app modules?

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
}
like image 805
Dr.Knowitall Avatar asked Jan 27 '14 00:01

Dr.Knowitall


People also ask

Can an Angular app have multiple modules?

Yes, you can define multiple modules in angularJS as given below. The modularization in AngularJS helps us to keep the code clarity and easy to understand, as we can combine multiple modules to generate the application.

How many modules are there in Angular app?

Only one root module can exist in an Angular application.

How do I know if Angular application is running in production or development mode?

Simply check the production variable present in the environment file, it will be true for production mode and false for development.

Is app module is mandatory in Angular?

The root app module is a necessary portion of every Angular app.


1 Answers

  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, []);
  }
}
like image 165
m59 Avatar answered Nov 14 '22 23:11

m59