4

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

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

我已经非常喜欢使用模板缓存在我的指令模板中注入 HTML 内容。现在有了 Angular 1.5,所有酷孩子都在使用这个新东西,叫做component ()(不在控制器中)?

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

4

2 回答 2

6

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

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

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

谷歌搜索的几个链接:

希望它会有所帮助。

于 2016-05-17T20:39:18.787 回答
3

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/

于 2016-05-17T21:38:24.867 回答