Marco Aurélio Deleu Marco Aurélio Deleu - 6 months ago 87
MySQL Question

Dependency injection in Angular Components like directives

Here's one thing I'm used to do with angular directives

angular.module('app.directives').directive('login', ['$templateCache', function ($templateCache) {
return {
restrict: 'E',
template: $templateCache.get('directives/login/login.html'),
controller: 'LoginController as vm',
scope: true
};
}]);


I've grown very attached to using Template Cache to inject HTML content in my directive's template. Now with Angular 1.5 there's this new thing all the cool kids are using called component() which I'm giving a look to see if it's really good and I'm stuck at this very beginning part: how to inject things in the component itself (not in the controller)?

In this case you can see that I'm injecting into the login directive the $templateCache dependency. How would I rewrite this directive as a component? (keeping in mind my desire to use $templateCache over templateUrl)

Answer

Well, In Angular 1.5 components, template property can be a function and this function is injectable (documentation).

So, you can just use something like:

...
template: ['$templateCache', function ($templateCache) {
   return $templateCache.get('directives/login/login.html')
}]
...

Few links from google search: one and two.

Hope it will help.

Comments