How to check for the existence of a module without an error being raised? How to check for the existence of a module without an error being raised? angularjs angularjs

How to check for the existence of a module without an error being raised?


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.

try { angular.module("ngRoute") } catch(err) { /* failed to require */ }

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.

var tryModules = function(names) {  // accepts a list of module names and  // attempts to load them, in order.  // if no options remain, throw an error.  if( names.length == 0 ) {    throw new Error("None of the modules could be loaded.");  }  // attempt to load the module into m  var m;  try {    m = angular.module(names[0])  } catch(err) {    m = null;  }  // if it could not be loaded, try the rest of  // the options. if it was, return it.  if( m == null ) return tryModules(names.slice(1));  else return m;};tryModules(["ngRoute", "ui.router"]);


I would test for the service instead of the module itself.

// In controllerif($injector.has('$route')){}if($injector.has('$state')){}// In angular configif($injector.has('$routeProvider')){}if($injector.has('$stateProvider')){}


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:

var initialModules = [  {name: 'app.directives', deps: ['ui.mask']},  {name: 'app.services'},  {name: 'app.templates'},  {name: 'app.controllers'}];initialModules.forEach(function(moduleDefinition) {  findOrCreateModule(moduleDefinition.name, moduleDefinition.deps);});function findOrCreateModule(moduleName, deps) {  deps = deps || [];  try {    angular.module(moduleName);  } catch (error) {    angular.module(moduleName, deps);  }}///// OR... in like "myDirective.js"findOrCreateModule('app.directives').directive('myDirective', myDirectiveFunction);