service $cacheFactory

构造缓存对象并访问它们的工厂。

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");

// We've specified no options on creation
expect(cache.info()).toEqual({id: 'cacheId', size: 2});

用法:$cacheFactory(cacheId, [options]);

参数:cacheId String 新创建的缓存的名称或id。

   options(optional)指定缓存行为的选项对象。属性:{number=} capacity-将缓存转换为LRU缓存。

返回:object 新创建的缓存对象,有以下方法:{object} info() — 返回id、大小和缓存的选项。{{*}} put({string} key, {*} value) — 将一个新的键值对放入缓存并返回它。{{*}} get({string} key) — 返回key对应的值。{void} remove({string} key) — 从缓存中删除键值对。{void} removeAll() — 清除所有缓存值。{void} destroy() — 从$cacheFactory删除对该缓存的引用。

方法:

info():获取已创建的所有缓存的信息。返回值:object 返回缓存的信息。

get(cacheId):通过在创建时使用的cacheId访问缓存对象。参数:cacheId String 缓存的名字。返回值:object 缓存对象由cacheId标识,如果没有这样的缓存,也没有定义。

例子:

index.html

<!DOCTYPE html>
<html ng-app="indexApp">
<head lang="en">
    <meta charset="UTF-8">
    <title>BookStore</title>
</head>
<body  ng-controller="firCtrl">
<div>
    <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><!--输出的是cache缓存对象的信息-->
    <div ng-repeat="(key, value) in cache.info()">
        <span ng-bind="key"></span>
        <span>: </span>
        <b ng-bind="value"></b>
    </div>
</div>
<script src="framework/angular.js"></script>
<script src="myJs/index.js"></script>
</body>
</html>

script.js

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

 

posted @ 2017-06-20 14:22  发福大叔  阅读(536)  评论(1编辑  收藏  举报