Cache in AngularJS allows us to save data into browser temporary memory. This data is available only for the life time of the page. As soon as page is refreshed or loaded again the data gets removed.
In this post, we shall learn how to add data into Cache. In order to do this, we shall use AngularJS $cacheFactory
service.
In below <script> block, we have declared an ng-app and ng-controller that has been injected with two object $scope
and $cacheFactory
.
In the controller method, we have declared cacheKeys
array property that will be used to store cache keys created by us so that we can iterate them to list.
Next, we have got a new reference of cache object (cacheObject
) by using $cacheFactory service by passing a unique name.
We have also declared an add
function that accepts key and value as input parameters. In this function, we are using cacheObject.put method to save new data into cache against the key. We are also pushing that key into the cacheKeys
array.
<script>
var app = angular.module("app", []);
app.controller("CacheController", ['$scope', '$cacheFactory', function ($scope, $cacheFactory) {
$scope.cacheKeys = [];
$scope.cacheObject = $cacheFactory("newCacheInstance");
$scope.add = function (key, value) {
$scope.cacheObject.put(key, value);
$scope.cacheKeys.push(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>
</div>
<hr />
<ol>
<li ng-repeat="key in cacheKeys">
<span ng-bind="key"></span> : <span ng-bind="cacheObject.get(key)"></span>
</li>
</ol>
<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, we have two text boxes for cache key and value with ng-model as cacheKey and cacheValue parameter respectively.
On click of the "Add" button, we are passing these two models to the "add" function that saves the data into cache against key entered in the key text box.
We are also iterating through each key and its value in the ordered list. Notice that we are able to get each cache key value using cacheObject.get(key)
.
At last, we are also iterating through cacheObject by calling .info()
method that tells us details about the cache object instance, number of keys present in the cache and any other optional parameter passed while creating this cache object.