最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to check if an Angular app already has running app modules? - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

1 Answer 1

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, []);
  }
}
发布评论

评论列表(0)

  1. 暂无评论