Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 685
Marco Aurélio Deleu Avatar asked Jan 06 '23 01:01

Marco Aurélio Deleu


2 Answers

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.

like image 140
MaKCbIMKo Avatar answered Jan 08 '23 14:01

MaKCbIMKo


MaKCblMKo 's answer is right, but remember that AngularJS will check the templateCache first before going out to to retrieve the template. Therefore, you don't have to make this call in your directive or component.

angular.module('myApp', [])
.component('myComponent',{
    templateUrl: 'yourGulpPattern'
})
.run(function($templateCache) {
    $templateCache.put('yourGulpPattern', 'This is the content of the template');
});

https://jsfiddle.net/osbnoebe/6/

like image 20
Zach Avatar answered Jan 08 '23 16:01

Zach