Angular Module Declarations Are Error Prone

Sometimes it’s the little things that can really trip you up. This particular one comes up on IRC often enough that I decided to write it up.

The most common error is:

Error: Unknown provider

The most common cause is an incorrectly declared or referenced Angular module.

Angular is built on a system of modules, providers and dependency injection.  As always with Javascript this is all done using functions to construct internal data structures that have no special meaning to the language itself.  This means that errors are usually opaque and deep inside angular code.

Here’s how you declare an Angular module.

angular.module("ModuleName", ["ModuleImport1", "ModuleImport2"], optionalConfigFn);

And here’s how you reference a module so you can declare providers (e.g. services):


The above is necessary when a module’s providers are in multiple files.

The reality is that many developers have only one module and so their module declaration looks like this:

angular.module("ModuleName", [])

And so a very common mistake is to reference a module as follows:

angular.module("ModuleName", []);

I think this is because many people also declare a module the same way, with no other module references. If you do this then Angular will moronically create another module and lose the original module. I’d love to understand for which scenarios this makes sense. My first pull request to Angular will be to turn that into an exception.
Another solution would be to avoid overloading:

angular.declareModule("ModuleName", dependencyArray, optionalConfigFn);

angular.findModule("ModuleName").service("myService", [function() {}]);