$templateCache
第一次使用模板,它被加載到模板緩存中,以便快速檢索。你可以直接將模板標簽加載到緩存中,或者通過$templateCache服務。
通過script標簽:
This is the content of the template
備注:script標簽模板不需要包含在文檔頭部。但他必須在$rootElement下,不然模板將會被忽略。
通過$templateCache服務:
(function() {
angular.module("Demo", [])
.run(["$templateCache",templateCache])
.controller("testCtrl", ["$templateCache","$sce",testCtrl]);functiontemplateCache($templateCache){
$templateCache.put('templateId.html', 'This is the content of the template');
}functiontestCtrl($templateCache,$sce) {vartpl = $templateCache.get('templateId.html');
tpl=$sce.trustAsHtml(tpl);this.text =tpl;
};
}());
在上面調用模板的代碼中,可以使用controller里的代碼調用緩存里的模板,但是需要注意的是,需要使用$sce轉成受信任的html插入代碼,所以這里需要注入$sce服務。而且這邊不止可以使用js調用,也可以直接在html里標簽里使用ng-include調用。
$templateRequest
$templateRequest服務運行進行安全檢測,然后使用$http下載被提供的模板,成功后,將內容存儲在$templateCache里。如果HTTP請求失敗或HTTP請求的響應數據是空的,將拋出個$compile錯誤(通過設置該函數的第二個參數為true)。該注意的是,$templateCache的內容是可信的,所以調用$sce.getTrustedUrl(tpl)是省略的,當tpl的類型是字符串并且$templateCache具有匹配的項。
使用:$templateRequest(tpl,[ignoreRequestError]);
tpl:字符串或者TrustedResourceUrl,HTTP請求URL的模板。
ignoreRequestError:boolean值,當請求失敗或模板為空時,是否忽略該異常。
使用代碼:
(function() {
angular.module("Demo", [])
.run(["$templateCache",templateCache])
.controller("testCtrl", ["$templateRequest","$sce",testCtrl]);functiontemplateCache($templateCache){
$templateCache.put('templateId.html', 'This is the content of the template');
}functiontestCtrl($templateRequest,$sce) {varvm =this;
$templateRequest("templateId.html").then(function(html){
vm.text=$sce.trustAsHtml(html);
})
};
}());