【拿来主义】Angularjs标签模板text/ng-template加载原理

前言

Angularjs提供多种模板加载方案。

最基础的为通过预先声明路径的方式,通过Ajax获取。
使用诸如gulp-html2js构建工具,将HTML模板转化为js文件使用。
使用script标签引入。
一般实际情况下,开发时使用第一种方式,部署时采取第二种方式,不会采用第三种方式。本文简要说明一下标签引入模板。Angularjs本身支持的标签type为text/ng-template,现在来支持另一种type:text/template。

相关的一篇博文:angular模板加载 ----ng-template

代码实现

从上一篇博文已经说明,$templateCache内的模板优先级最高,所以需要使用到。angularjs本身采取将script指令化的方式来实现。

var scriptDirective = ['$templateCache', function($templateCache) {
  return {
    restrict: 'E',
    terminal: true,
    compile: function(element, attr) {
      if (attr.type == 'text/ng-template') {
        var templateUrl = attr.id,
            text = element[0].text;
        $templateCache.put(templateUrl, text);
      }
    }
  };
}];

代码非常简单,判定类型---写入模板即可。封装后完全看不到内部实现,所以才会再用个人方式实现,用以理解。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Inline Template</title>
    <script type="text/template" id="love">
        <h3>love is color blind</h3>
        <p>why so serious about the world, behind the darkness</p>
    </script>
    <script src="libs/angular.min.js"></script>
    <script src="libs/angular-sanitize.min.js"></script>
    <script src="js/template.js"></script>
</head>
<body ng-app="template">
    <article ng-controller="TemplateCtrl">
        <div ng-bind-html="story"></div>
    </article>
</body>
</html>
angular.module('template', ['ngSanitize'])
  .run(['$document', '$templateCache', function($document, $templateCache) {
    var scripts = Array.prototype.slice.call($document[0].scripts, 0);
    scripts.forEach(function(script) {
      if (script.type === 'text/template') {
        $templateCache.put(script.id, script.innerHTML);
      }
    });
  }])
  .controller('TemplateCtrl', ['$scope', '$templateCache', '$log', function($scope, $templateCache, $log) {
    $scope.story = $templateCache.get('love');
  }]);

代码非常简单,即通过document.scripts这样接近原始的方式来获取对应标签,然后将标签内部的内容写入$templateCache即可。

预览地址:http://120.24.59.102/inline.html

使用该模板的方法:

app.directive('myDirective', function($templateCache,$compile) {
    return {
        restrict: 'A',
        scope:{
            template : "@",
            mydata : "=",
            mycallback:"&"
        },
        link: function(scope,element) {
            var template = $templateCache.get(scope.template);
            scope.values = scope.mydata;
            scope.doSomething = scope.mycallback;
            element.append($compile(template)(scope));
        }
    }
});

本文来源

Angularjs标签模板加载原理

转载于:https://www.cnblogs.com/shih/p/6971729.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值