layout: post
title: Angular@1.4.3 中文 API 服務篇 $templateCache & $templateRequest
desc: '關于模板的兩個服務,緩存和請求'
categories: jekyll update
$templateCache
- ng模塊中的服務
在模板第一次被引用時,它會被載入到模板緩存中以便快速的檢索。你可以直接使用一個script標簽來添加一個
模板,或者直接通過 $templateCache
服務來達到相同的效果。
通過 script 標簽添加:
html
<script type="text/ng-template" id="templateId.html">
<p>This is the content of the template</p>
</script>
注意:script 標簽包含的模板并不需要 document
的頭部,但它必須是 $rootElement
的
后代(IE,帶有 ng-app
屬性的元素),否則這個模板將被忽略掉。
通過$templateCache
服務添加:
javascript
var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
$templateCache.put('templateId.html', 'This is the content of the template');
});
在檢索模板之后,你就可以在你的 HTML 里輕松的使用了。
html
<div ng-include=" 'templateId.html' "></div>
或者通過 Javascript 得到它 :
javascript
$templateCache.get('templateId.html')
請看 $cacheFactory
.
$templateRequest
- ng模塊中的服務
$templateRequest
服務
$templateRequest
服務使用 $http
服務下載模板,并在之后進行安全檢測。如果成功,
則內容會被存儲到 $templateCache
中。如果HTTP請求失敗或者該請求的響應數據為空,
會拋出一個編譯($compile
)錯誤(這個行為可以通過將函數的第二個參數設置為 true
來阻止)。
需要注意的是,$templateCache
的內容是可以信任的,因此當 tpl
是以字符串形式出現的時候,
或者通過 $templateCache
作為入口時,是可以不必去調用 $sce.getTrustedUrl(tpl)
來驗證的。
用法
$templateRequest(tpl, [ignoreRequestError]);
參數
參數 | 形式 | 詳細 |
---|---|---|
tpl |
string TrustedResourceUrl
|
HTTP 請求的模板路徑(URL) |
ignoreRequestError (可選) | boolean |
是否忽略請求失敗或者模板為空的情況 |
返回
promise
- 一個表示通過給定的路徑請求得到的 HTTP 相應數據的 promise
屬性
totalPendingRequests
- number
- 所有被需求下載模板的總數