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.javascript
Let’s start with a simple example: a directive autocompleting the user input.java
<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.nginx
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.web
scope
, even though we may not need it.Now, contrast it with the Angular 2 way of defining the same directive.typescript
@Decorator({selector: '[autocomplete]'}) class Autocomplete { constructor(autocompleter:Autocompleter, el:NgElement, attrs:NgAttributes){ //... } }
Or if you prefer ES5app
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.less
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.ide
<div> <input name="title" autocomplete="movie-title"> <input name="actor" autocomplete="actor-name"> </div>
The matching injector tree:post
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.ui
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.