ng的缓存模板的用法

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

script tag

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

方式一

html:
<body ng-app="demoModule">
    <div ng-controller="demoCtrl">
        <demo-directive></demo-directive>
    </div>
    
    <script type="text/ng-template" id="templateId.html">
        <a>template cache content</a>
    </script>
    
</body>

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:
<body ng-app="demoModule">
    <demo-directive></demo-directive>
</body>

js:

angular.module('demoModule', [])
    .directive('demoDirective', demoDirectiveFn)
    .run(['$templateCache', templateCacheFn]);
    
function templateCacheFn($templateCache) {
    var tpl = ‘<a ng-click="test()">This is the content of the template {{:: name}}</a>’;
    $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:
<body ng-app="demoModule">
    <div ng-controller="demoCtrl">
        <div ng-bind-html="template"></div>
    </div>
</body>

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 = ‘<a ng-click="test()">This is the content of the template {{:: name}}</a>’;
    $templateCache.put('templateCache.html', tpl);
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值