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
}
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.
Only one root module can exist in an Angular application.
Simply check the production variable present in the environment file, it will be true for production mode and false for development.
The root app module is a necessary portion of every Angular app.
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, []);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With