Mastering Web Application

(Rick Simeone) #1

Angular Zen


Modules and dependency injection


Vigilant readers have probably noticed that all the examples presented so far were
using global constructor functions to define controllers. But global state is evil, it
hurts application structure, makes code hard to maintain, test, and read. By no
means is AngularJS suggesting usage of global state. On the contrary, it comes
with a set of APIs that make it very easy to define modules and register objects
in those modules.


Modules in AngularJS

Let's see how to turn an ugly, globally-defined controller definition into its
modular equivalent, before a controller is declared as follows:


var HelloCtrl = function ($scope) {
$scope.name = 'World';
}

And when using modules it looks as follows:


angular.module('hello', [])
.controller('HelloCtrl', function($scope){
$scope.name = 'World';
});

AngularJS itself defines the global angular namespace. There are various utility
and convenience functions exposed in this namespace, and module is one of those
functions. A module acts as a container for other AngularJS managed objects
(controllers, services, and so on). As we are going to see shortly, there is much
more to learn about modules than simple namespacing and code organization.


To define a new module we need to provide its name as the very first argument
to the module function call. The second argument makes it possible to express
a dependency on other modules (in the preceding module we don't depend on
any other modules).


A call to the angular.module function returns an instance of a newly created
module. As soon as we've got access to this instance, we can start defining new
controllers. This is as easy as invoking the controller function with the
following arguments:



  • Controller's name (as string)

  • Controller's constructor function

Free download pdf