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。如许不需要将模块文件嵌入到营业代码当中去,同时只需要修正指令的配置文件就好。

    原文作者:苹果小萝卜
    原文地址: https://segmentfault.com/a/1190000004473937
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞