angular.module("module") is an anti pattern

 

There are two ways to use the angular.module() function. There is the call with one parameter, that returns an existing module and there is an option of using two parameter which creates a new module. The second way, where a new module is created, is perfectly fine and should be used. However the first option, where an existing module is loaded should be considered and anti pattern in most cases and should not be used unless there is an exceptional and very good reason.

 

What is wrong with angular.module(“module”)?

Why should this usage be seen as an anti pattern? Well both creating and retrieving using angular.module() returns the module so it can be extended. And that is exactly where the problem is. When you create a new module in a JavaScript file you can use that reference to add anything you want, no need to load it again. So the only place loading an exiting module is needed is when you want to add something to it in another JavaScript file.

Splitting modules introduces a big risk. As soon as you split an AngularJS module into separate files you can run into the possibility of loading a partially configured module. Where AngularJS checks if all module dependencies can be satisfied at load time it has no way of seeing if these modules are complete or not.  Missing a complete module produces a very clear error message right at startup time like this:

Uncaught Error: [$injector:modulerr] Failed to instantiate module mainApp due to:
Error: [$injector:modulerr] Failed to instantiate module mainApp.data due to:
Error: [$injector:nomod] Module ‘mainApp.data’ is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you

As the complete application fails to load very obvious and hard not to spot.

 

However if you fail to load just a part of a module the errors are a lot less obvious. In this case the error doesn’t appear until the missing component is actually needed, everything up to that point will run just fine.  The king of error message you will see is something like:

Error: [$injector:unpr] Unknown provider: productsProvider <- products

The error in itself is clear enough but discovering it might not be as easy. If the error occurs in a part of that application that is not used often it might go completely unnoticed.

 

My rule of the thumb: Always define a complete AngularJS module in one JavaScript file.

 

Want to split the functionality into multiple files. By all means go ahead but make sure to do so in a new module and take use module dependencies to make sure everything is loaded right at the application start time. And as angular.module(“module”) is only required to load a module defined in another file there really should almost never be a need to use it.

Enjoy!

Leave a Reply

Your email address will not be published. Required fields are marked *