Chapter 1
Globally-defined controller's constructor functions are only good for
quick-code examples and fast prototyping. Never use globally-defined
controller functions in larger, real life applications.
A module is defined now, but we need to inform AngularJS about its existence. This
is done by providing a value to the ng-app attribute as follows:
<body ng-app="hello">
Forgetting to specify a module's name in the ng-app attribute is
a frequent mistake and a common source of confusion. Omitting
a module name in the ng-app attribute will result in an error
indicating that a controller is undefined.
Collaborating objects
As we can see, AngularJS provides a way to organize objects into modules. A module
can be used not only to register objects that are directly invoked by the framework
(controllers, filters, and so on) but any objects defined by applications' developers.
Module pattern is extremely useful to organize our code, but AngularJS goes one
step further. In addition to registering objects in a namespace, it is also possible to
declaratively describe dependencies among those objects.
Dependency injection
We could already see that the $scope object was being mysteriously injected into
controllers' instances. AngularJS is somehow able to figure out that a new scope
instance is needed for a controller, and then creates a new scope instance and
injects it. The only thing that controllers had to do was to express the fact that it
depends on a $scope instance (no need to indicate how a new $scope object should
be instantiated, should this $scope instance be a newly created one or reused from
previous calls). The whole dependency management boils down to saying something
along those lines: "To function correctly I need a dependency (collaborating object): I
don't know from where it should be coming or how it should be created. I just know
that I need one, so please provide it".
AngularJS has the dependency injection (DI) engine built in. It can perform the
following activities:
- Understand a need for a collaborator expressed by objects
- Find a needed collaborator
- Wire up objects together into a fully-functional application