2016-05-17 113 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