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

})

};

}());

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,073评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 33,044评论 18 399
  • 22年12月更新:个人网站关停,如果仍旧对旧教程有兴趣参考 Github 的markdown内容[https://...
    tangyefei阅读 35,309评论 22 257
  • AngularJS是什么?AngularJs(后面就简称ng了)是一个用于设计动态web应用的结构框架。首先,它是...
    200813阅读 5,577评论 0 3
  • 今天我是主持人 通过昨天的磨合,小伙伴的凝聚力又提升了 莉塔分享的五行朋友圈(金木水火土)非常棒 感谢团队小伙伴今...
    5de7b70be210阅读 1,445评论 0 0

友情链接更多精彩内容