Mastering Web Application

(Rick Simeone) #1
Chapter 1

Since AngularJS combines all the services from all the modules into one big,
application-level set of services there can be one and only one service with a
given name. We can use this to our advantage in cases where we want to depend
on a module, but at the same time override some of the services from this module.
To illustrate this, we can redefine the dieselEngine service directly in the cars
module in the following manner:


angular.module('app', ['engines', 'cars'])
.controller('AppCtrl', function ($scope, car) {
car.start();
});

angular.module('cars', [])
.factory('car', function ($log, dieselEngine) {
return {
start: function() {
$log.info('Starting ' + dieselEngine.type);
};
}
})

.factory('dieselEngine', function () {
return {
type: 'custom diesel'
};
});

In this case, the car service will be injected with the dieselEngine service
defined in the same module as that of the car service. The car module level,
dieselEngine, will override (shadow) the dieselEngine service defined under
the engines module.


There can be one and only one service with a given name in an
AngularJS application. Services defined in the modules closer to the
root of modules hierarchy will override those defined in child modules.

In the current version of AngularJS, all the services defined on one module are
visible to all the other modules. There is no way of restricting service's visibility
to one module or a subset of modules.


At the time of writing, there is no support provided for
module-private services.
Free download pdf