【拿來主義】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標簽模板加載原理


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM