天天看點

Angularjs标簽模闆加載原理

前言

Angularjs

提供多種模闆加載方案。

  • 最基礎的為通過預先聲明路徑的方式,通過Ajax擷取。
  • 使用諸如

    gulp-html2js

    建構工具,将

    HTML

    模闆轉化為

    js

    檔案使用。
  • 使用

    script

    标簽引入。

一般實際情況下,開發時使用第一種方式,部署時采取第二種方式,不會采用第三種方式。本文簡要說明一下标簽引入模闆。

Angularjs

本身支援的标簽

type

text/ng-template

,現在來支援另一種

type

text/template

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

代碼實作

從上一篇博文已經說明,

$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[].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[].scripts, );
    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

即可。

ria