AngularJs $templateCache 和 $templateRequest 模板緩存

$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);

})

};

}());

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,991評論 19 139
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,767評論 18 399
  • 22年12月更新:個人網站關停,如果仍舊對舊教程有興趣參考 Github 的markdown內容[https://...
    tangyefei閱讀 35,235評論 22 257
  • AngularJS是什么?AngularJs(后面就簡稱ng了)是一個用于設計動態web應用的結構框架。首先,它是...
    200813閱讀 1,653評論 0 3
  • 今天我是主持人 通過昨天的磨合,小伙伴的凝聚力又提升了 莉塔分享的五行朋友圈(金木水火土)非常棒 感謝團隊小伙伴今...
    5de7b70be210閱讀 186評論 0 0