由于浏览器加载html模板是异步加载的,如果加载大量的模板会拖慢网站的速度,这里有一个技巧,就是先缓存模板。
使用angular缓存模板主要有三种方法:
方法一:通过script标签引入
注意,这里的id只是指十几使用模板时的一个引用,而不是一个url, 模板的实际内容在script标签里。ng-template指明这是angular模板。
当然,模板的实际内容我们也可以使用themeleaf的标签来引用一些html页面,如th:include和th:replace。
th:replace和th:include的参数格式是:templatename::[domselector]表示引入模板页面中的某个模块。
其中templatename引入模板页面,domselector引入自身模板的模块。
注意:script标签模板不需要包含在文档头部。但他必须在$rootElement下,不然模板将会被忽略。
方法二:通过$templateCache服务来实现
angular.module('myApp', []) .controller('myCtrl', ['$scope','$templateCache', function($scope,$templateCache){ var tmp = 'hello
' + '这是直接调用$templateCache服务获取模板文件的方式
' + '服务启用templateCache方式'; $templateCache.put('hello.html',tmp); }])
$templateCache的put()方法负责向内存中写入模板内容,然后在directive中用controllerUrl:'hello.html'就可以使用,甚至可以使用ng-include="'hello.heml'"来调用。
ng-include的方式:
<div ng-app="myApp" ng-controller="myCtrl as ctrl"> <div ng-include="'hello.html'">div> div>
directive的方式:
angular.module('myApp', []) .directive('templateDemo', ['$log', function($log){ return { restrict: 'A', templateUrl: 'hello.html', replace: true, link: function($scope, iElm, iAttrs, controller) {} } }]) //html
$templateCache基于cacheFactory,接口保持一致,方法主要有:
方法 | 说明 |
---|---|
put | 向内存写入模板内容 |
get | 从内存获取模板内容 |
remove | 传入key值,删除对应模板内容 |
removeAll | 删除所有模板内容 |
destroy | 解除key-value对应关系,但不释放内存 |
info | 模板缓存对象的信息 |
方法三:$templateCache和ng-bind-html
<div ng-app="Demo" ng-controller="testCtrl as ctrl"> <div ng-bind-html="ctrl.text">div> div>
angular.module("Demo", []) .run(["$templateCache",templateCache]) .controller("testCtrl", ["$templateCache","$sce",testCtrl]); function templateCache($templateCache){ $templateCache.put('templateId.html', 'This is the content of the template'); } function testCtrl($templateCache,$sce) { var tpl = $templateCache.get('templateId.html'); tpl = $sce.trustAsHtml(tpl); this.text = tpl; }; }
注意:使用ng-bind-html就要使用\$sce转成受信任的html插入代码。