Angular 1.x has two APIs for injecting dependencies into a directive. These APIs are not interchangeable, so depending on what you are injecting, you need to use one or the other. Angular 2 unifies the two APIs, making the code easier to understand and test.
ANGULAR 1.X
Let’s start with a simple example: a directive autocompleting the user input.
<input name="title" autocomplete="movie-title">
The autocomplete directive takes the user input, and using the autocompleter service object, gets matching movie titles from the backend.
module.directive('autocomplete', ["autocompleter", function(autocompleter) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
//...
}
}
}]);
Note, we have to use two mechanisms to inject the autocompleter and the element.
- The autocompleter service is injected into the directive factory function, and it is done by name.
- The element and the attributes are injected into the link function. This is done by position, which forces us to pass in
scope
, even though we may not need it.
ANGULAR 2
Now, contrast it with the Angular 2 way of defining the same directive.
@Decorator({selector: '[autocomplete]'})
class Autocomplete {
constructor(autocompleter:Autocompleter, el:NgElement, attrs:NgAttributes){
//...
}
}
Or if you prefer ES5
function Autocomplete(autocompleter, el, attrs) {
//...
}
Autocomplete.annotations = [new Decorator({selector: '[autocomplete]'})];
Autocomplete.parameters = [[Autocompleter], [NgElement], [NgAttributes]];
In Angular 2 the autocompleter, the element, and the attributes are injected into the constructor by name.
HIERARCHICAL INJECTORS
How is it possible? Should not every instance of the directive get its own element? It should. To enable that the framework builds a tree of injectors that matches the DOM.
<div>
<input name="title" autocomplete="movie-title">
<input name="actor" autocomplete="actor-name">
</div>
The matching injector tree:
Injector Matching Div
|
|__Injector Matching Movie Title
|
|__Injector Matching Actor Name
Since there is an injector for every DOM element, the framework can provide element-specific information, such as an element, attributes, or a shadow root.
SUMMARY
In Angular 2 there is a single way to inject dependencies into a directive, regardless of what you inject: user-defined services, framework services, elements, attributes, or other directives.