AngularJS提供多种模板加载
2017-05-04 22:27
281 查看
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[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即可。
相关文章推荐
- Freemarker提供了3种加载模板目录的方法
- AngularJS模板加载用法详解
- Jquery使用ajax以及angularjs 动态模板加载并进行渲染
- --@angularJS--模板加载之缓存模板demo
- Freemarker提供了3种加载模板目录的方法
- AngularJS实现根据变量改变动态加载模板的方法
- Angularjs标签模板加载原理
- 【拿来主义】Angularjs标签模板text/ng-template加载原理
- angularjs 动态加载js文件,可在模板
- Angularjs 异步模块加载项目模板
- angularjs 封装百度地图API(实现异步加载)
- wince控件之自绘按钮(支持多种状态的图像加载、可通过图像创建不规程按钮)
- 动态下载苹果提供的多种中文字体
- Android MVP设计框架模板 之 漂亮ListView上拉刷新下拉加载更多
- ListView里item加载多种布局文件
- 利用grunt+browserify预编译js模板文件,支持commonJS加载
- AngularJS拖动窗口滑块以加载更多
- AngularJS入门教程01:静态模板
- AngularJS中多种过滤器的使用