Ⅱ.AngularJS的点点滴滴--缓存 - cnljli

模板缓存- $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 创建的的对象,有如下方法

  1. {object} info() — 返回大小、id、一些缓存的参数
  2. {value} put(key,value) — 插入键值对,键为字符串,值为任何类型,返回键值对中的值
  3. {value} get(key) —通过键返回值,如果不存在返回 undefined
  4. {void} remove(key) — 通过键来移除,无返回值
  5. {void} removeAll() — 移除所有的模板缓存,无返回值
  6. {void} destroy() —移除当前创建的缓存( $templateCache 无效)

$cacheFactory 有所创建的对象直接通过 $cacheFactory('cacheID',[,option])

其中的 option 对象主要有 capacity 参数为数字类型设置最大的列表长度, 默认值为 Number.MAX_VALUE ,当超过的时候最早的会被移除,当设置最长长度为2的时候, 方法如下

  $cacheFactory('cache',{capacity:2});

获取的时候调用 get 方法参数为cache的ID即可,当不存在时返回 undefined

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值