How to check for the existence of a module without

2019-01-21 18:59发布

In Angular 1.2, ngRoute is a separate module so you can use other community routers like ui.router instead.

I'm writing an open-source module that aims to work for multiple different router implementations. So how can I check which router is loaded or exists?

I'm doing the following inside a factory in my module, but it does not work the way I expect it to:

if (angular.module("ngRoute"))
  // Do ngRoute-specific stuff.
else if (angular.module("ui.router"))
  // Do ui.router-specific stuff.

It raises an error for whichever module is not loaded. For example, if the app is using ui.router, then the following error is raised for the ngRoute check:

Uncaught Error: [$injector:nomod] Module 'ngRoute' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

7条回答
Deceive 欺骗
2楼-- · 2019-01-21 19:28

AngularJS 1.6.3 and up has a way to check if a module is loaded via the $injector service.

Also added in 1.6.7 was the ability to load new modules which may be of interest to some.

查看更多
登录 后发表回答