AngularJs $templateCache 和 $templateRequest 模板緩存


$templateCache

第一次使用模板,它被加載到模板緩存中,以便快速檢索。你可以直接將模板標簽加載到緩存中,或者通過$templateCache服務。

通過script標簽

<script type=”text/ng-template” id=”template.html”>

<p>This is the content of the template</p>

</script>

備注:script標簽模板不需要包含在文檔頭部。但他必須在$rootElement下,不然模板將會被忽略。

通過$templateCache服務:

  <div ng-app="Demo" ng-controller="testCtrl as ctrl">
    <!--<div ng-include="'templateId.html'"></div>-->
    <div ng-bind-html="ctrl.text"></div>
  </div>
  (function () {
    angular.module("Demo", [])
    .run(["$templateCache",templateCache])
    .controller("testCtrl", ["$templateCache","$sce",testCtrl]);
    function templateCache($templateCache){
      $templateCache.put('templateId.html', '<a>This is the content of the template</a>');
    }
    function testCtrl($templateCache,$sce) {
        var tpl = $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]);
    function templateCache($templateCache){
      $templateCache.put('templateId.html', '<a>This is the content of the template</a>');
    }
    function testCtrl($templateRequest,$sce) {
        var vm = this;
        $templateRequest("templateId.html").then(function(html){
            vm.text = $sce.trustAsHtml(html);
        })
    };
  }());


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM