2016-05-17 581 views
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依赖项。我如何将这个指令重写为一个组件? (记住我希望使用$ templateCache over templateUrl)

回答

5

那么,在角度为1.5的组件中,template属性可以是一个函数,这个函数是可注入的(documentation)。

所以,你可以使用类似:

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

从谷歌搜索几个环节:onetwo

希望它会有所帮助。

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/

+0

它不是把内容在那里,我有一个大口的任务,minifies和“放”在模板缓存处理的每个HTML文件。我只需要访问元素,以便检索它的内容。 –

+0

这很酷,但我想说的是,如果你的吞咽任务做了'放',那么你仍然不需要触摸$ templateCache。只需引用url,它就会从缓存中抓取它,因为它已经存在。我举的例子只是表明它已经在缓存中。换句话说 - 想象一下,在我的例子中,run函数是你的一个重要任务......除非我仍然不明白你在说什么。 – Zach

+0

只需引用templateUrl,让角从你的$ templateCache中为它拉动。我希望更清楚。我没有试图告诉你如何将它放入缓存中。 – Zach