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:
1 2 3 |
angular.module('tutsocean').controller('articleCtrl', function($scope) { $scope.title = "Learn AngularJS"; }); |
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:
1 2 3 4 |
angular.module('tutsocean').controller('articleCtrl', function() { var $scope = new angular.Scope(); $scope.title = "Learn AngularJS"; }); |
In this snippet, the responsibility for the construction and use of the $scope
dependency 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.