我正在處理需要將HTML綁定到富文本編輯器的表單。存儲此HTML內容的最佳方式是HTML文件。將文件中的HTML模板加載到AngularJs中的變量中
我不能完全弄清楚如何從文件加載HTML模板並將其分配給變量。
當使用templateUrl時,指令似乎確實能做到這一點。想知道是否有角度上的任何低級別的api在控制器內實現同樣的東西
我正在處理需要將HTML綁定到富文本編輯器的表單。存儲此HTML內容的最佳方式是HTML文件。將文件中的HTML模板加載到AngularJs中的變量中
我不能完全弄清楚如何從文件加載HTML模板並將其分配給變量。
當使用templateUrl時,指令似乎確實能做到這一點。想知道是否有角度上的任何低級別的api在控制器內實現同樣的東西
所有模板都加載到緩存中。有一個注射$templateCache服務,您可以用它來獲得的模板訪問:
app.controller('testCtrl', function($scope, $templateCache){
var template = $templateCache.get('nameOfTemplate.html');
});
使用$templateRequest
,你可以通過它的URL,而無需將其嵌入到HTML頁面加載模板。如果模板已經加載,它將從緩存中取出。
app.controller('testCtrl', function($scope, $templateRequest, $sce, $compile){
// Make sure that no bad URLs are fetched. You can omit this if your template URL is
// not dynamic.
var templateUrl = $sce.getTrustedResourceUrl('nameOfTemplate.html');
$templateRequest(templateUrl).then(function(template) {
// template is the HTML template as a string
// Let's put it into an HTML element and parse any directives and expressions
// in the code. (Note: This is just an example, modifying the DOM from within
// a controller is considered bad style.)
$compile($("#my-element").html(template).contents())($scope);
}, function() {
// An error has occurred
});
});
要知道,這是手工的方式來做到這一點,和而在大多數情況下,最好的辦法是define一個directive,其獲取使用templateUrl
屬性的模板。
嗨,cdauth,任何想法如何與平面html模板一起加載JS。 –
真棒!!!!我正在尋找這個,非常感謝你! – Oswaldo
如果模板是使用'。或者您可以使用$ http服務手動獲取模板並使用'$ templateCache.put'來存儲它們。 – dustyrockpyle
好 - 完美。這涵蓋了我正在尋找的場景。謝謝! –