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

Dependency injection in Angular Components like directives

这是我习惯用 angular 指令做的一件事

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
    };
}]);

我越来越喜欢使用 Template Cache 在我的指令模板中注入 HTML 内容。现在有了 Angular 1.5,所有酷孩子都在使用这个名为 component() 的新东西,我正在看它是否真的好,我被卡住了在最开始的部分:如何在组件本身(而不是控制器)中注入东西?

在这种情况下,您可以看到我正在向 login 指令中注入 $templateCache 依赖项。我如何将这个指令重写为一个组件? (记住我希望在 templateUrl 上使用 $templateCache)

嗯,在Angular 1.5 组件中,template 属性 可以是一个函数,并且这个函数是可注入的(documentation)。

所以,您可以使用类似的东西:

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

来自 google 搜索的几个链接:one and two

希望对您有所帮助。

MaKCblMKo 的回答是正确的,但请记住,AngularJS 会先检查 templateCache,然后再去检索模板。因此,您不必在指令或组件中进行此调用。

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/