Wednesday, 5 November 2014

Introduction to AngularJS - Part 4

Dependency Injection

We mentioned it before, but it bears repeating that there’s a lot going on with Hello
Controller that we didn’t have to write. For example, the $scope object that does our
data binding is passed to us automatically; we didn’t have to create it by calling any
function. We just asked for it by putting it in HelloController’s constructor.

As we’ll find out in later post, $scope isn’t the only thing we can ask for. If we want
to data bind to the location URL in the user’s browser, we can ask for an object that
manages this by putting $location in our constructor, like so:

function HelloController($scope, $location) {
 $scope.greeting = { text: 'Hello' };
 // use $location for something good here...
}

We get this magical effect through Angular’s dependency injection system. Dependency
injection lets us follow a development style in which, instead of creating dependencies,
our classes just ask for what they need.

This follows a design pattern called the Law of Demeter, also known as the principle of
least knowledge. Since our HelloController’s job is to set up the initial state for the
greeting model, this pattern would say that it shouldn’t worry about anything else, like
how $scope gets created, or where to find it.

This feature isn’t just for objects created by the Angular framework. You can write the
rest of this code as well.

No comments:

Post a Comment