Wscats / angular-tutorial

:rabbit:Some of the angular tutorial - 《Angular学习笔记》

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

$cacheFactory

Wscats opened this issue · comments

$cacheFactory可以用来进行数据在controller之间传递

var cache = $cacheFactory('wsscat');
用**$cacheFactory**方法设置一个缓存,并赋给一个对象,该对象拥有下面的这些方法

  • put(key,value);
  • 在缓存对象中插入一个键值对(key,value)
  • get(key);
  • 在缓存对象中通过指定key获取对应的值
  • romove(key);
  • 在缓存对象中通过指定key删除对应的值
  • removeAll();
  • 删除缓存对象中所有的键值对
  • destroy();
  • 销毁这个缓存对象
  • info();
  • 获取缓存对象信息(id,size)

用**$cacheFactory**在控制器之间交换数据要注意的是,如果刷新页面,数据就不复存在,所以在做单页面应用时候,如果想在不同视图不同控制器之间交换数据,这种方法慎用

其实**$cacheFactory**在控制器交换数据等同于自定义一个服务,然后在自定义服务中交换数据

app.controller('pageMain1Ctrl', function($scope, $cacheFactory) {
            var cache = $cacheFactory('wsscat');
            cache.put('name', 'wsscat');
            cache.put('age', 0);
            var info = cache.info();
            console.log(info);
        })

app.controller('pageMain2Ctrl', function($scope, $state, $cacheFactory) {
            var cache = $cacheFactory.get('wsscat');
            var name = cache.get('name');
            console.log(name);
        })

这里写图片描述