简体   繁体   English

Angular组件中的依赖注入,如指令

[英]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. 我已经非常依赖于使用模板缓存在我的指令模板中注入HTML内容。 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)? 现在有了Angular 1.5,所有很酷的孩子都使用了这个新东西叫做component() ,我正在看看它是否真的很好而且我在这个最开始的部分陷入困境:如何在组件本身注入东西(不在控制器中)?

In this case you can see that I'm injecting into the login directive the $templateCache dependency. 在这种情况下,您可以看到我正在向login指令注入$ templateCache依赖项。 How would I rewrite this directive as a component? 我如何将此指令重写为组件? (keeping in mind my desire to use $templateCache over templateUrl) (请记住我希望在templateUrl上使用$ templateCache)

Well, In Angular 1.5 components, template property can be a function and this function is injectable ( documentation ). 好吧,在Angular 1.5组件中, template属性可以是一个函数,这个函数是可注入的( 文档 )。

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. 希望它会有所帮助。

MaKCblMKo 's answer is right, but remember that AngularJS will check the templateCache first before going out to to retrieve the template. MaKCblMKo的答案是正确的,但请记住AngularJS将在出去检索模板之前先检查templateCache。 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/ https://jsfiddle.net/osbnoebe/6/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM