Reputation: 1340
I would like to test if a module is already created. Is it possible to check it with simple code like shown below?
if(angular.module('myApp') == undefined){
angular.module('myApp', ['ngRoute']);
}
Upvotes: 0
Views: 47
Reputation: 149
The following worked for me - then if the file got inserted twice into the main index.html file - the angular module would only be created once.
var myApp = myApp;
if (!myApp) {
myApp = angular.module('myApp', []);
}
Upvotes: 0
Reputation: 106385
No, it's not that easy. If angular.module
is called with a single argument - the name of the module - it always throws an Error unless module is already there (source):
if (!requires) {
throw $injectorMinErr('nomod', "Module '{0}' 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.", name);
}
The point is mostly the same as with import clauses in other languages: if you do import a module (most probably as a dependency of another) and it's not there yet, it's a serious error - a show-stopper of a sort, hence an Error (and not just returning null
or something).
And there's no easy way to access modules' list: it's stored in a variable local to moduleLoader. So one possible approach to solve this is wrap the check in try-catch
:
function isModuleRegistered(moduleName) {
var isThere = true;
try {
angular.module(moduleName);
}
catch {
isThere = false;
}
return isThere;
}
Still I have to say if there's a need for such trick, it's a code smell. Angular has a nice (not perfect, but nice) dependency injection system, and it's not that hard to couple it with different loaders (like RequireJS, for example). If you need to manually check whether or not a module is there yet, most probably there's a deficiency out there waiting to bite you back. )
The only exception I can think about is a system that might work with different implementations of a single interface - and needs to check which one is supplied; but then again, that's easier to solve on a configuration level.
Upvotes: 1
Reputation: 20445
More better way can be with try catch block
try {
var myApp= angular.module("myApp") ;
}
catch(err)
{
angular.module('myApp', ['ngRoute']);
}
Upvotes: 0