前言
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));
}
}
});