$cacheFactory

标签: AngularJS API 中文


  • ng模块中的服务
    以工厂模式构造cache对象,并且使它们可以被访问。

javascript

var cache = $cacheFactory('cacheId');

expect($cacheFactory.get('cacheId')).toBe(cache);
expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();

cache.put("key", "value");
cache.put("another key", "another value");

// 创建时我们没有指定配置项
expect(cache.info()).toEqual({id: 'cacheId', size: 2});


用法

$cacheFactory(cacheId, [配置项]);

参数 形式 具体
cacheId string 新缓存的名称或ID。
配置项 (选填) object 配置对象会指定缓存的行为。 性能:

{number=} 容量 — 将缓存转化成LRU缓存。

返回

--- ---
object 新创建的缓存对象有以下的配置方法:

- {object} info() — 返回 id, 大小, 和缓存的配置。

- {{*}} put({string} key, {*} value) — 向缓存中插入以个新的键值对并将它返回。

- {{*}} get({string} key) — 返回与key对应的value值,如果未命中则返回undefined

- {void} remove({string} key) — 从缓存中删除一个键值对

- {void} removeAll() — 删除所有缓存中的数据

- {void} destroy() — 删除从$cacheFactory引用的这个缓存.

方法

info(); 获取所有被创建的缓存的信息

返回

Object 返回一个关于cacheId的键值

get(cacheId); 如果与cacheId相对应的缓存对象被创建,则获取它

参数

参数 形式 具体
cacheId string 一个可以通过的缓存名字或ID

返回

Returns
Object - 通过 cacheId 确认的缓存对象,或是确认失败的 undefined


例子

html

<div ng-controller="CacheController">

  <input ng-model="newCacheKey" placeholder="Key">
  <input ng-model="newCacheValue" placeholder="Value">
  
  <button ng-click="put(newCacheKey,newCacheValue)">Cache</button>

  <p ng-if="keys.length">Cached Values</p>
  <div ng-repeat="key in keys">
    <span ng-bind="key"></span>
    <span>: </span>
    <b ng-bind="cache.get(key)"></b>
  </div>

  <p>Cache Info</p>
  <div ng-repeat="(key, value) in cache.info()">
    <span ng-bind="key"></span>
    <span>: </span>
    <b ng-bind="value"></b>
  </div>
</div>

javascript

angular.module('cacheExampleApp', []).
controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  $scope.keys = [];
  $scope.cache = $cacheFactory('cacheId');
  $scope.put = function(key, value) {
    if ($scope.cache.get(key) === undefined) {
      $scope.keys.push(key);
    }
    $scope.cache.put(key, value === undefined ? null : value);
  };
}]);

css

p {
  margin: 10px 0 3px;
}

本文由作者原创,翻译内容仍有欠佳之处,请大家多多指正。via 村里有个村长 / @西瓜橘子葡萄冰

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 面试题一:https://github.com/jimuyouyou/node-interview-questio...
    R_X阅读 1,638评论 0 5
  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 9,285评论 0 3
  • 前端开发面试题 面试题目: 根据你的等级和职位的变化,入门级到专家级,广度和深度都会有所增加。 题目类型: 理论知...
    怡宝丶阅读 2,606评论 0 7
  • 本文旨在加深对前端知识点的理解,资料来源于网络,由本人(博客:http://segmentfault.com/u/...
    风起云帆阅读 334评论 0 0
  • 本文旨在加深对前端知识点的理解,资料来源于网络,由本人(博客:http://segmentfault.com/u/...
    AuthorJim阅读 446评论 0 0