In previous post, we learnt what is caching in AngularJS and how to add data into cache in AngularJS. In this post, we shall learn how to read data from cache and how to update existing data of the cache.
Important: It is mandatory to read previous post in order to understand this post.
In below <script> block, we have added update
and read
function in the controller. To update data of the cache, we pass existing key and new value into the cacheObject.put method. Passing existing keys, modifies existing cache data.
To read data from cache, we use cacheObject.get method by passing key as parameter.
<script>
var app = angular.module("app", []);
app.controller("CacheController", ['$scope', '$cacheFactory', function ($scope, $cacheFactory) {
$scope.cacheKeys = [];
$scope.cacheData = '';
$scope.cacheObject = $cacheFactory("newCacheInstance");
$scope.add = function (key, value) {
$scope.cacheObject.put(key, value);
$scope.cacheKeys.push(key);
};
$scope.update = function (key, value) {
$scope.cacheObject.put(key, value);
};
$scope.read = function (key) {
$scope.cacheData = $scope.cacheObject.get(key);
};
}]);
</script>
<div ng-app="app" ng-controller="CacheController">
Cache key: <input type="text" ng-model="cacheKey" placeholder="cacheKey"/>
Cache value: <input type="text" ng-model="cacheValue" placeholder="cacheValue" />
<div><br />
<button ng-click="add(cacheKey, cacheValue)">Add</button>
<button ng-click="read(cacheKey)">Read</button>
<button ng-click="update(cacheKey, cacheValue)">Update</button>
</div>
<hr />
<ol>
<li ng-repeat="key in cacheKeys">
<span ng-bind="key"></span> : <span ng-bind="cacheObject.get(key)"></span>
</li>
</ol>
Cache data: <span ng-bind="cacheData"></span>
<hr />
<b>Cache info</b>
<ul>
<li ng-repeat="(key, value) in cacheObject.info()">
<span ng-bind="key"></span> : <span ng-bind="value"></span>
</li>
</ul>
</div>
In the HTML block, clickiong on Update button calls update
functions by passing existing key (written into the key textbox) and value written into the value text box. Clicking on Read button calls read
function by passing key text box value.
Remaining code that lists cache data and other details have already been explained in the previous post.
Views: 11531 | Post Order: 64