Mastering Web Application

(Rick Simeone) #1
Chapter 1

Modules depending on other modules

Not only does AngularJS do the excellent job of managing object dependencies, but
in addition it takes care of inter-module dependencies. We can easily group related
services into one module, and thus create (potentially re-usable) service libraries.


As an example, we could move both the notifications and archiving services into
their own modules (named notifications and archive, respectively) as follows:


angular.module('application', ['notifications', 'archive'])

This way each service (or a group of related services) can be combined into
a re-usable entity (a module). Then the top-most (application-level) module
can declare dependencies on all the modules needed for proper functioning
of a given application.


The ability to depend on other modules is not reserved for the top-most modules.
Each module can express dependencies on its child modules. In this way, modules
can form a hierarchy. So, when dealing with AngularJS modules we need to think
about two distinct, but related, hierarchies: modules hierarchy and services hierarchy
(as services can express dependencies on other services, values, and constants).


AngularJS modules can depend on each other and every module can contain several
services. But individual services can also depend on other services. This raises
several interesting questions, which are as follows:



  • Can a service defined in one AngularJS module depend on services in
    another module?

  • Can services defined in a child module depend on a service in a parent
    module, or only on services defined in child modules?

  • Can we have module-private services visible only in a certain module?

  • Can we have several services with the same name defined in
    different modules?


Services and their visibility across modules


As one might expect services defined in child modules are available for injection
into services in parent modules the following code example should make it clear:


angular.module('app', ['engines'])

.factory('car', function ($log, dieselEngine) {
return {
start: function() {
$log.info('Starting ' + dieselEngine.type);
};
Free download pdf