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.
I am not aware of a way of checking without an error being raised; however, notice that the issue is that it was an
Uncaught Error
, not that an error was thrown. The pattern for catching such an error is the following.If an error is caught, you can try the other module, and if not, you can use the first.
If your behavior will be the same for each module, you could do something like the following, in which we define a function which will attempt the first of the listed module names, and if an error is thrown, try the next option.
The original answer is legit. However, as an alternative, I wrote this when I needed to "find or create" the modules. There's a number of use cases, but generally, it lets you not have to worry about file load order. You could either put this in a
initialModules.js
... or the top of all your individual service/directive files start with something like this. This little function works like a charm for me:If you decorate
angular.module
to store the names in an array then you could just check if the array contains your module name.Decorate angular.module
See @dsfq's answer on SO.
This needs to happen after angular is loaded but before you start loading any angular modules.
Check for your module
if(angular.modules.indexOf("ngRoute") > -1) ...
The problem of automatically load or create a module could be better solved by something like gulp-angular-filesort, though. It works really flawlessly.
From gulp-angular-filesort github page: Automatically sort AngularJS app files depending on module definitions and usage
Used in conjunction with gulp-inject to inject your AngularJS application files (scripts) in a correct order, to get rid of all Uncaught Error: [$injector:modulerr].
Disclaimer: I'm not affiliated with gulp-angular-filesort, I only use it with a lot of profit.
I would test for the service instead of the module itself.
A much better solution is to simply do your check when the module is created. You just need a utility function to add a callback.