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);
        })
    };
  }());
复制代码
posted @   野兽'  阅读(12522)  评论(1编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示