Mastering Web Application

(Rick Simeone) #1
Chapter 2

Inside a module


As soon as a module is declared it can be used to register recipes for the object's
creation. As a reminder, those recipes are called providers in AngularJS terminology.
Each provider, when executed, will produce exactly one run-time service instance.
While recipes for services creation can be expressed using multitude of forms
(factories, services, providers and variables) the net effect is always the same; a
configured instance of a service.


Different syntax for registering providers

To register a new provider we need to get a hand on a module's instance first. It
is easy as a module instance will be always returned from a call to the angular.
module method.


We could save a reference to the returned module instance and reuse it to register
multiple providers. For example, to register two controllers on the module
responsible for managing projects we could write:


var adminProjects = angular.module('admin-projects', []);

adminProjects.controller('ProjectsListCtrl', function($scope) {
//controller's code go here
});

adminProjects.controller('ProjectsEditCtrl', function($scope) {
//controller's code go here
});

While this approach certainly works it has one drawback; we are obliged to declare
an intermediate variable (adminProjects in this case) just to be able to declare
multiple providers on a module. Worse yet, the intermediate variable could end up
in the global namespace if we don't take additional precautions (wrapping module
declaration into a closure, creating a namespace, and so on.). Ideally, we would like
to be able to somehow retrieve an instance of an already declared module. It turns
out that we can do this as shown in the next example:


angular.module('admin-projects', []);

angular.module('admin-projects').controller('ProjectsListCtrl',
function($scope) {
//controller's code goes here
});
Free download pdf