Open In App

AngularJS $cacheFactory Service

Last Updated : 14 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The $cacheFactory service in AngularJS is a factory function that creates new instances of the Cache object, which is a simple in-memory cache that stores key-value pairs. The Cache object is useful for storing data that is expensive to retrieve, such as data that comes from a server or data that is computed using a complex algorithm. By storing the data in the cache, you can avoid the overhead of retrieving it each time it is needed, and improve the performance of your application.

To use the $cacheFactory service, you first it needed to be injected into your AngularJS component as a dependency. For example

angular.module('myModule', [])
  .controller('MyController', function($scope, $cacheFactory) {
    // Use the $cacheFactory service here
  });

Once injected, the $cacheFactory service into your component, you can use it to create a new Cache object by calling the $cacheFactory function with a name for the cache. For example:

var myCache = $cacheFactory('myCache');

Syntax:

$cacheFactory(cacheId, [options]);

Parameters: It accepts 2 parameters:

  • cacheId: It accepts a string type that specifies the id or name for the newly cache created.
  • options: It is an optional parameter that specifies the behavior of the cache.

Return values: The Cache object has the following methods:

  • put(key, value): Stores a value in the cache under the specified key.
  • get(key): Retrieves the value stored in the cache under the specified key.
  • remove(key): Removes the value stored in the cache under the specified key.
  • removeAll(): Removes all values stored in the cache.
  • destroy(): Removes all values stored in the cache and destroys the cache object.

Approach 1: We have an AngularJS application with a single controller, MyController. We have injected the $cacheFactory service into the controller as a dependency, and we have used it to create a new Cache object with the name myCache.

We have also defined three functions in the controller: store, retrieve, and remove. The store function stores a value in the cache under the specified key. The retrieve function retrieves the value stored in the cache under the specified key. The remove function removes the value stored in the cache under the specified key. The key and value are entered by the user into the input elements in the form. The functions are called when the user clicks the corresponding buttons.

Example 1: This example describes the basic usage of the $cacheFactory service in AngularJS

HTML




<!DOCTYPE html>
<html ng-app="myApp">
 
<head>
    <script src=
    </script>
    <style>
        h1 {
            color: green
        }
 
        input {
            width: 100px;
            padding: 5px 15px;
            margin: 5px 0;
            box-sizing: border-box;
            border: 2px solid #ccc;
            border-radius: 4px;
        }
 
        button {
            color: white;
            background-color: black;
            height: 30px;
            width: 100px;
            padding: 3px;
            margin: 5px;
            border-radius: 5px;
        }
    </style>
    <script>
        angular.module('myApp', [])
            .controller('MyController', function ($scope, $cacheFactory) {
                var myCache = $cacheFactory('myCache');
 
                $scope.key = '';
                $scope.value = '';
 
                $scope.store = function () {
                    myCache.put($scope.key, $scope.value);
                    $scope.key = '';
                    $scope.value = '';
                }
 
                $scope.retrieve = function () {
                    $scope.value = myCache.get($scope.key);
                }
 
                $scope.remove = function () {
                    myCache.remove($scope.key);
                    $scope.key = '';
                    $scope.value = '';
                }
            });
    </script>
</head>
 
<body ng-controller="MyController">
    <center>
        <h1> GeeksforGeeks</h1>
        <h3>
            AngularJS $cacheFactory service
        </h3>
        <form>
            <label>Key:</label>
            <input type="text" ng-model="key" /><br>
            <label>Value:</label>
            <input type="text" ng-model="value" /><br>
            <button ng-click="store()">Store</button>
            <button ng-click="retrieve()">Retrieve</button>
            <button ng-click="remove()">Remove</button>
        </form>
    </center>
</body>
 
</html>


Output:

 

Approach 2: We have an AngularJS application with a single controller, MyController. We have injected the $cacheFactory service into the controller as a dependency, and we have used it to create a new Cache object with the name fibonacciCache.

We have also defined a function in the controller called calculate. This function calculates the nth number in the Fibonacci sequence using a recursive function called calculateFibonacci. If the result is already stored in the fibonacciCache, it is retrieved from the cache and returned to the controller. If the result is not in the cache, it is calculated using the calculateFibonacci function, stored in the cache, and returned to the controller. The user enters the value of n into the input element in the form, and the calculate function is called when the user clicks the “Calculate” button. The result is displayed in the p element below the form.

Example 2: This example describes the basic implementation of the $cacheFactory service in AngularJS, where we have created a calculateFibonacci function that calculates the nth number in the Fibonacci sequence using a recursive function.
 

HTML




<!doctype html>
<html ng-app="myApp">
 
<head>
    <script src=
    </script>
    <style>
        h1 {
            color: green
        }
 
        input {
            width: 100px;
            padding: 5px 15px;
            margin: 5px 0;
            box-sizing: border-box;
            border: 2px solid #ccc;
            border-radius: 4px;
        }
 
        button {
            color: white;
            background-color: black;
            height: 30px;
            width: 100px;
            padding: 3px;
            margin: 5px;
            border-radius: 5px;
        }
    </style>
 
</head>
 
<body ng-controller="MyController">
    <center>
        <h1> GeeksforGeeks</h1>
        <h3>AngularJS $cacheFactory service</h3>
        <h5> Fibonacci Number calculator</h5>
        <form>
            <label>Enter number:</label>
            <input type="text" ng-model="n" /><br>
            <button ng-click="calculate()">Calculate</button>
        </form>
        <p>Result: {{result}}</p>
    </center>
    <script>
        angular.module('myApp', [])
            .controller('MyController', function ($scope, $cacheFactory) {
                var fibonacciCache = $cacheFactory('fibonacciCache');
 
                $scope.n = '';
                $scope.result = '';
 
                $scope.calculate = function () {
                    var n = parseInt($scope.n);
                    if (isNaN(n)) return;
 
                    var result = fibonacciCache.get(n);
                    if (result) {
                        $scope.result = result;
                        return;
                    }
 
                    result = calculateFibonacci(n);
                    fibonacciCache.put(n, result);
                    $scope.result = result;
                }
 
                function calculateFibonacci(n) {
                    if (n === 0 || n === 1) return n;
                    return calculateFibonacci(n - 1) + calculateFibonacci(n - 2);
                }
            });
    </script>
</body>
 
</html>


Output:

 

Reference: https://docs.angularjs.org/api/ng/service/$cacheFactory



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads