標簽: 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");
// 創(chuàng)建時我們沒有指定配置項
expect(cache.info()).toEqual({id: 'cacheId', size: 2});
用法
$cacheFactory(cacheId, [配置項]);
| 參數(shù) | 形式 | 具體 |
|---|---|---|
cacheId |
string |
新緩存的名稱或ID。 |
| 配置項 (選填) | object |
配置對象會指定緩存的行為。 性能: {number=} 容量 — 將緩存轉化成LRU緩存。 |
返回
| --- | --- |
|---|---|
object |
新創(chuàng)建的緩存對象有以下的配置方法: - {object} info() — 返回 id, 大小, 和緩存的配置。- {{*}} put({string} key, {*} value) — 向緩存中插入以個新的鍵值對并將它返回。- {{*}} get({string} key) — 返回與key對應的value值,如果未命中則返回undefined。 - {void} remove({string} key) — 從緩存中刪除一個鍵值對 - {void} removeAll() — 刪除所有緩存中的數(shù)據(jù) - {void} destroy() — 刪除從$cacheFactory引用的這個緩存. |
方法
info();獲取所有被創(chuàng)建的緩存的信息
返回
Object 返回一個關于cacheId的鍵值
get(cacheId);如果與cacheId相對應的緩存對象被創(chuàng)建,則獲取它
參數(shù)
| 參數(shù) | 形式 | 具體 |
|---|---|---|
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;
}
本文由作者原創(chuàng),翻譯內容仍有欠佳之處,請大家多多指正。via 村里有個村長 / @西瓜橘子葡萄冰