Modules

Every AngularJS app is built out of at least one module — the container that holds your controllers, services, and configuration, and the thing ng-app actually points at. You've already used angular.module() in passing; this lesson covers what it's really doing.

Creating a module vs getting one

angular.module() behaves differently depending on whether you pass a second argument, and mixing this up is the single most common beginner mistake in AngularJS:

JS app.js
// CREATES a new module named 'myApp' — note the [] array, even if empty
var app = angular.module('myApp', []);

// RETRIEVES the existing 'myApp' module — no array argument
var sameApp = angular.module('myApp');
What actually happens
app and sameApp both refer to the same module object. The [] on the first
call is what tells AngularJS "define a new module" instead of "look one up" —
drop it, and angular.module('myApp') throws:
  Error: [$injector:nomod] Module 'myApp' is not available!

The empty array is a list of other modules this one depends on — empty means "no dependencies," not "no array." Forgetting it entirely is what turns a module-creation call into a module-lookup call by accident, which is why this specific mistake trips up nearly everyone learning AngularJS at least once.

Registering things on a module

Controllers, services, filters, and directives are all registered by chaining calls off the module object — the pattern you've already seen with .controller():

JS app.js
var app = angular.module('myApp', []);

app
  .controller('HomeController', function($scope) { /* ... */ })
  .controller('ProfileController', function($scope) { /* ... */ })
  .service('UserService', function() { /* ... */ });

Each of those registration methods returns the module itself, which is why they can be chained one after another instead of repeating app. every time.

Depending on another module

Real apps split into multiple modules — one per feature area is a common pattern — and list each other as dependencies in that array you saw earlier:

JS app.js
var userModule = angular.module('userModule', []);
var app = angular.module('myApp', ['userModule']);

myApp can now use anything userModule registered — its controllers, services, and so on — as if they'd been defined directly on myApp itself.

Unknown provider errors: if you reference a service by name but forget to list the module that defines it as a dependency, AngularJS fails at startup with an error like Unknown provider: UserServiceProvider <- UserService. It's a confusing message the first time you see it, but it always means the same thing: something needs a piece that its module's dependency array doesn't actually include.