博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ng的缓存模板的用法
阅读量:7072 次
发布时间:2019-06-28

本文共 2017 字,大约阅读时间需要 6 分钟。

使用ng缓存模板的方式大致有三种:

script tag

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

方式一

html:    
js:angular.module('demoModule', []) .controller('demoCtrl', ['$scope', '$sce', '$templateCache', demoCtrlFn]) .directive('demoDirective', ['$templateCache', demoDirectiveFn]); function demoDirectiveFn($templateCache) { restrict: 'EA', template: function() { return document.getElementById('templateId.html') }}

PS: 指令ng-template所在script标签必须在ng-app指令的内部,否则无法被angular context编译。

$templateCache服务

$templateCache+$sce配合ng-bind-html="templateId.html"

or 在directive里面使用templateUrl指定模板

方式二:

html:    
js:angular.module('demoModule', []) .directive('demoDirective', demoDirectiveFn) .run(['$templateCache', templateCacheFn]); function templateCacheFn($templateCache) { var tpl = ‘This is the content of the template {
{:: name}}
’; $templateCache.put('templateCache.html', tpl);}function demoDirective(){ return { restrict: 'EA', templateUrl: 'templateCache.html', link: function(scope, ele, attr){ scope.test = function() { console.log(123); } scope.name = 'Hello templateCache'; } }}

方式三(在controller里面调用缓存模板):

html:    
js:angular.module('demoModule', []) .controller('demoCtrl', ['$sce', '$templateCache', '$scope', demoCtrl]) .run(['$templateCache', templateCacheFn]); function demoCtrl($sce, $templateCache, $scope) { var tpl = $templateCache.get('template.html'); //调用$sce,设置为可信用的html代码然后插入模板 tpl = $sce.trustAsHtml(tpl); $scope.template = tpl; $scope.test = function() { console.log(123); } $scope.name = 'Hello templateCache';} function templateCacheFn($templateCache) { var tpl = ‘This is the content of the template {
{:: name}}
’; $templateCache.put('templateCache.html', tpl);}

一般编写自定义指令的时候更推荐使用方式2。这样不需要将模块文件嵌入到业务代码当中去,同时只需要修改指令的配置文件就好。

转载地址:http://huell.baihongyu.com/

你可能感兴趣的文章
chest
查看>>
hdu 1215 七夕节
查看>>
老调重弹:JDBC系列 之 &lt;驱动载入原理全面解析&gt;
查看>>
UVa11183 - Teen Girl Squad(最小树形图-裸)
查看>>
高速排序--双边扫描与单边扫描的实现
查看>>
android去除标题栏和状态栏
查看>>
[转]利用 NPOI 變更字體尺寸及樣式
查看>>
eval解析JSON字符串的一个小问题
查看>>
jquery简单原则器(匹配除了指定选择器之外的元素 selector 表示选择器)
查看>>
update使用inner join
查看>>
Vue2.x中的父子组件相互通信
查看>>
多种替身邮方法总结!
查看>>
沟通比文档更有力
查看>>
在页面头部<!DOCTYPE html ....> 前面不能有任何输出
查看>>
hdu 2102 A计划(双层BFS)(具体解释)
查看>>
大型机器学习
查看>>
FluentNhibernate 不支持存储过程
查看>>
Python 修改电脑DNS
查看>>
复杂 Listview 显示 多个样式
查看>>
[Unity3D]Unity3D游戏开发之角色控制漫谈
查看>>