[关闭]
@bornkiller 2014-12-10T15:05:39.000000Z 字数 1694 阅读 2488

Angularjs标签模板加载原理

angularjs


前言

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

一般实际情况下,开发时使用第一种方式,部署时采取第二种方式,不会采用第三种方式。本文简要说明一下标签引入模板。Angularjs本身支持的标签typetext/ng-template,现在来支持另一种typetext/template

相关的一篇博文:https://www.zybuluo.com/bornkiller/note/6023

代码实现

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

  1. var scriptDirective = ['$templateCache', function($templateCache) {
  2. return {
  3. restrict: 'E',
  4. terminal: true,
  5. compile: function(element, attr) {
  6. if (attr.type == 'text/ng-template') {
  7. var templateUrl = attr.id,
  8. text = element[0].text;
  9. $templateCache.put(templateUrl, text);
  10. }
  11. }
  12. };
  13. }];

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

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

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

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

联系方式

QQ: 491229492

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注