<!DOCTYPE html>
<html lang="en" ng-app="testDirectiveTemplateUrl">
<head>
<meta charset="UTF-8">
<title>测试DirectiveTemplateUrl</title>
<script src="../frameWork/angular.js"></script>
<script src="../testDirective/testDirectiveTemplateUrl.js"></script>
<script type="text/ng-template" id="templateUrlTwo">
<div>
<span>我是来自templateUrlTwo的内容</span>
</div>
</script>
<script type="text/ng-template" id="templateUrlDynamic1">
<div>
<span>我是来自动态templateUrlDynamic1的内容</span>
</div>
</script>
<script type="text/ng-template" id="templateUrlDynamic2">
<div>
<span>我是来自动态templateUrlDynamic2的内容</span>
</div>
</script>
</head>
<body>
<h3>内容1:正常的模版来源</h3>
<template-url-normal></template-url-normal>
<h3>内容2:模版来自script标签</h3>
<template-url-from-script></template-url-from-script>
<h3>内容3:模版来自script标签,并且动态的模版</h3>
<template-url-dynamic></template-url-dynamic>
<template-url-dynamic template-index="1"></template-url-dynamic>
<template-url-dynamic template-index="2"></template-url-dynamic>
</body>
</html>
/**
* 由于directive在angular中的地位之重,所以得认真对待。但理解难啊,所以决定逐个属性进行实例分析
* directive实例分析第四篇:templateUrl
* Created by liyanq on 16/12/21.
*/
/**templateUrl很重要的属性,正常情况下,应该都会用到吧。
* 1,templateUrl的值'directive.html', // or // function(tElement, tAttrs) { ... }。
* 2,templateUrl函数执行的时机要早于link,并且如果找不到url的话,link就不执行了(很危险啊。。。)
* 3,templateUrl的大小写得注意。
* */
var app = angular.module("testDirectiveTemplateUrl",[]);
app.directive("templateUrlNormal",function($templateCache){
var dir = {};
dir.restrict = "E";
dir.replace = true;
dir.templateUrl = $templateCache.get("templateUrlOne");
return dir;
}).directive("templateUrlFromScript",function(){
var dir = {};
dir.restrict = "E";
dir.replace = true;
dir.templateUrl = "templateUrlTwo";
return dir;
}).directive("templateUrlDynamic",function(){
var dir = {};
dir.restrict = "EA";
dir.replace = true;
dir.scope=true;
dir.templateUrl = function(scope,attr){
if (attr["templateIndex"]){//如果解析不了,得给个默认的
return "templateUrlDynamic"+attr["templateIndex"];
}
return "templateUrlDynamic1";
};
return dir;
}).run(function($templateCache){
$templateCache.put("templateUrlOne","../templates/testTemplateUrlOne.html");
});