模板缓存- $templateCache and 缓存工厂 $cacheFactory
1.使用script标签
<html ng-app>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular.js"></script>
<body>
<div ng-include='"test"'></div>
<script type="text/ng-template" id="test">
This is the content of the template
</script>
</body>
</html>
如果使用 script 标签,那么就要加上type为 text/ng-template
ng-include 的值必须用 '""' 或者 "''" ,只有一个单引号或者双引号的时候会无效
2.使用js脚本
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular.js"></script>
<body>
<div ng-include='"test"'></div>
<script>
angular.module('app.ui', [])
.run(['$templateCache','$cacheFactory',
function($templateCache,$cacheFactory) {
var cachetest = $cacheFactory('cache');
cachetest.put('a','This is the content of the template');
}]);
angular.module('app', ['app.ui'])
.run(['$templateCache','$cacheFactory',
function(temp,cache) {
var cachetest = cache.get('cache');
temp.put('test',cachetest.get('a') );
cachetest.destroy();
}]);
angular.bootstrap(document, ['app']);
</script>
</body>
</html>
$templateCache 里面存放的是键值对的数据,有 $cacheFactory 创建对象一样的方法
$cacheFactory 创建的的对象,有如下方法
- {object} info() — 返回大小、id、一些缓存的参数
- {value} put(key,value) — 插入键值对,键为字符串,值为任何类型,返回键值对中的值
- {value} get(key) —通过键返回值,如果不存在返回 undefined
- {void} remove(key) — 通过键来移除,无返回值
- {void} removeAll() — 移除所有的模板缓存,无返回值
- {void} destroy() —移除当前创建的缓存( $templateCache 无效)
$cacheFactory 有所创建的对象直接通过 $cacheFactory('cacheID',[,option])
其中的 option 对象主要有 capacity 参数为数字类型设置最大的列表长度, 默认值为 Number.MAX_VALUE ,当超过的时候最早的会被移除,当设置最长长度为2的时候, 方法如下
$cacheFactory('cache',{capacity:2});
获取的时候调用 get 方法参数为cache的ID即可,当不存在时返回 undefined