標(biāo)簽: AngularJS API 中文
-
ng模塊中的服務(wù)
以工廠模式構(gòu)造cache對(duì)象,并且使它們可以被訪問(wèn)。
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");
// 創(chuàng)建時(shí)我們沒(méi)有指定配置項(xiàng)
expect(cache.info()).toEqual({id: 'cacheId', size: 2});
用法
$cacheFactory(cacheId, [配置項(xiàng)]);
| 參數(shù) | 形式 | 具體 |
|---|---|---|
cacheId |
string |
新緩存的名稱或ID。 |
| 配置項(xiàng) (選填) | object |
配置對(duì)象會(huì)指定緩存的行為。 性能: {number=} 容量 — 將緩存轉(zhuǎn)化成LRU緩存。 |
返回
| --- | --- |
|---|---|
object |
新創(chuàng)建的緩存對(duì)象有以下的配置方法: - {object} info() — 返回 id, 大小, 和緩存的配置。- {{*}} put({string} key, {*} value) — 向緩存中插入以個(gè)新的鍵值對(duì)并將它返回。- {{*}} get({string} key) — 返回與key對(duì)應(yīng)的value值,如果未命中則返回undefined。 - {void} remove({string} key) — 從緩存中刪除一個(gè)鍵值對(duì) - {void} removeAll() — 刪除所有緩存中的數(shù)據(jù) - {void} destroy() — 刪除從$cacheFactory引用的這個(gè)緩存. |
方法
info();獲取所有被創(chuàng)建的緩存的信息
返回
Object 返回一個(gè)關(guān)于cacheId的鍵值
get(cacheId);如果與cacheId相對(duì)應(yīng)的緩存對(duì)象被創(chuàng)建,則獲取它
參數(shù)
| 參數(shù) | 形式 | 具體 |
|---|---|---|
cacheId |
string |
一個(gè)可以通過(guò)的緩存名字或ID |
返回
Returns
Object - 通過(guò) cacheId 確認(rèn)的緩存對(duì)象,或是確認(rèn)失敗的 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;
}
本文由作者原創(chuàng),翻譯內(nèi)容仍有欠佳之處,請(qǐng)大家多多指正。via 村里有個(gè)村長(zhǎng) / @西瓜橘子葡萄冰