菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
415
0

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

原创
05/13 14:22
阅读数 95097

模板缓存-$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.使用url地址文件

<html ng-app>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.2/angular.js"></script>
<body>
<div ng-include='"test.html"'></div>
</body>
</html>
  • 在目录下新建test.html文件即可

3.使用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


发表评论

0/200
415 点赞
0 评论
收藏
为你推荐 换一批