您的位置:首页 > Web前端 > AngularJS

--@angularJS--模板加载之缓存模板demo

2015-05-20 15:20 288 查看
不用缓存模板的写法如下:

1、index.html:

<!DOCTYPE HTML>
<html ng-app="app">
<head>
<title>directive-templateUrl</title>
<meta charset="utf-8">
<link rel="stylesheet" href="../css/bootstrap.css">
<script src="../js/angular.js"></script>
</head>
<body>
<!-- 下面是加载指令模板的总入口文件. -->
<div>
<!-- hello标签就代表了templateUrl中加载的模板碎片代码.注意:这样直接加载ff是没什么问题,chrome因为同源安全策略直接就不显示,解决办法是:用缓存模板(对象$templateCache) -->
<hello></hello>
</div>
</body>
<script src="hello.js"></script>
</html>

2、hello.js:

var myModule = angular.module("app",[]);
myModule.directive('hello',function(){
return {
restrict:'AE',
replace:true,
templateUrl:'helloTemplate.html'//helloTemplate.html文件表示的就是<div>Hi there</div>这一串html模板代码碎片文件,hello标签就代表这个模板
}
});

3、模板文件——helloTemplate.html:

<div>Hi there</div>

[解析]:

加载效果:ff页面显示Hi there.chrome页面空白

上面的注意部分已经说过,因为同源安全策略chrome并不显示模板文件,解决办法就是用缓存模板对象$templateCache来加载,那么我们下面来改造下js文件即可:

2、hello.js:

var myModule = angular.module("app",[]);
myModule.run(function($templateCache){
$templateCache.put("helloTemplate.html","<div>hello everyone.</div>");
});// 向缓存中存入模板文件,并用put()方法向模板文件写入<div>hello everyone.</div>这段代码.注意这段代码会覆盖模板文件原有的代码碎片
myModule.directive('hello',function($templateCache){
return {
restrict:'AE',
replace:true,
template:$templateCache.get("helloTemplate.html")// 用get()方法从缓存模板对象获取模板文件
}
});

[解析]:

加载效果:ff和chrome:页面均显示hello everyone.(原代码<div>Hi there</div>被覆盖)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: