AngularJS > Caching

Remove from cache in AngularJS

How to remove one or all items from cache in AngularJS?

In previous post, we learnt how to add, update, read data from cache in AngularJS. In this post, we shall learn how to remove item or all items from cache and even destroy the entire cache object.

Important: It is mandatory to read previous post in order to understand this post.

In below <script> block, we have three more buttons "Remove", "Remove All" and "Dispose Cache Object". These buttons will remove one item from cache, remove all items from cache and destroy the entire cache object respectively.

To remove one item, we are calling $scope.remove function by passing key that in tern calls $scope.cacheObject.remove function by passing key as parameter to remove that particular key value from the cache.

To remove all items, we are calling $scope.cacheObject.RemoveAll function in removeAll function that removes all items from the cache.

To destroy the entire cache object, we are calling $scope.cacheObject.destroy method in Dispose function.

    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.update = function (key, value) {
            $scope.cacheObject.put(key, value);

        $ = function (key) {
            $scope.cacheData = $scope.cacheObject.get(key);

        $scope.remove = function (key) {

        $scope.removeAll = function (key) {

        $scope.Dispose = function (key) {

<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>
        <button ng-click="remove(cacheKey)">Remove</button>
        <button ng-click="removeAll()">Remove All</button>
        <button ng-click="Dispose()">Dispose Cache Object</button>
    <hr />
        <li ng-repeat="key in cacheKeys">
            <span ng-bind="key"></span> : <span ng-bind="cacheObject.get(key)"></span>

    Cache data: <span ng-bind="cacheData"></span>
    <hr />

    <b>Cache info</b>
        <li ng-repeat="(key, value) in">
            <span ng-bind="key"></span> : <span ng-bind="value"></span>


HTML block is as simple as calling respective remove, removeAll and Dispose functions by calling "Remove", "Remove All" and "Dispose Cache Object" buttons.


AngularJS Cache add, remove, update, read

 Views: 3826 | Post Order: 65

Write for us