Injection in AngularJS

In the first directives section, we mentioned injection, stating that we would cover it in a later section. Injection might get a little complicated, but I’ll do my best to keep it concise and understandable.

Minimal theory

Dependency injection is a common software design pattern that is frequently used in any non-trivial application. By writing an AngularJS application, you will use dependency injection, even if you’re not aware of it. As such, it makes sense to learn a little of the theory behind the pattern.

The essence of the pattern is to separate the responsibilities of construction and usage of dependencies. In this tutorial, we have already seen an example of this, as follows:

In this snippet, articleCtrl is dependent on $scope in order to make model properties and behaviors available for binding. We do not know how $scope is constructed by AngularJS (nor do we really care), as long as we can use it withinarticleCtrl.

If we were to construct $scope ourselves, in a very simplified form it might look something like the following:

In this snippet, the responsibility for the construction and use of the $scopedependency is solely with articleCtrl. A principle of good software design is for a component, such as articleCtrl, to do one thing and to do it well.