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

时间:2016-05-17 19:40:23

标签: javascript angularjs angularjs-components

这是我以前用角度指令做的一件事

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()的新东西,我要看看它是否真的很好,我和#39; m停留在这个最开始的部分:如何在组件本身注入东西(而不是在控制器中)?

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

2 个答案:

答案 0 :(得分:5)

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

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

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

Google搜索中的链接很少:onetwo

希望它会有所帮助。

答案 1 :(得分: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/

相关问题