使用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。这样不需要将模块文件嵌入到业务代码当中去,同时只需要修改指令的配置文件就好。