AngularJS $cacheFactory Service
Last Updated :
14 Feb, 2023
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
Similar Reads
AngularJS $location Service
The $location in AngularJS basically uses a window.location service. The $location is used to read or change the URL in the browser and it is used to reflect that URL on our page. Any change made in the URL is stored in the $location service in AngularJS. There are various methods in the $location s
4 min read
AngularJS $controller Service
AngularJS applications depend on a controller to control the flow of data through an AngularJS application. AngularJS architecture uses the MVC model i.e the Model View Controller. The model is responsible for maintaining the application data, the View for displaying data or some part of data to the
5 min read
AngularJS $document Service
In AngularJS, a service is a function or object that is available for dependency injection (DI) in an AngularJS app. Services are typically used to encapsulate and reuse business logic and other app functionality that is not directly related to the presentation of data in the app. The $document serv
3 min read
AngularJS $parse Service
The $parse service in AngularJS is a function that takes an expression string and returns a function that can be used to parse and evaluate the expression. The expression string can contain variables, operators, and function calls. To use the $parse service, you first need to inject it into your Ang
3 min read
Angular.js $log Service
The $log service in Angular.js is simply used for logging purposes on the browser console. It is used for the debugging and troubleshooting of the error in the code. It has various implementations like a log, warn, info, error, and debugging, and all the names suggest. It is used for logging, warnin
5 min read
AngularJS $compile Service
The $compile service in AngularJS is used to compile an HTML template into a function that can be used to link the template to a scope. This service is typically used to compile dynamic templates that are generated on the fly, such as templates that are loaded from the server or created by a directi
4 min read
AngularJS $exceptionHandler Service
In AngularJS, a service is a function or object that is available for dependency injection (DI) in an AngularJS app. Services are typically used to encapsulate and reuse business logic and other app functionality that is not directly related to the presentation of data in the app. The $exceptionHand
4 min read
AngularJS $animateCSS Service
The $animateCss service in AngularJS allows developers to easily animate the addition or removal of CSS classes on an element. This feature can be useful for creating visually appealing transitions and adding polish to the user interface. To use the $animateCss service, the ngAnimate module must be
4 min read
AngularJS Services
The Services is a function or an object that avails or limit to the application in AngularJS, ie., it is used to create variables/data that can be shared and can be used outside the component in which it is defined. Service facilitates built-in service or can make our own service. The Service can on
4 min read
AngularJS $interval Service
The $interval service in AngularJS is a function that allows you to execute a function repeatedly at a specified interval. It is similar to the setInterval function in JavaScript, but it is designed to work seamlessly with the AngularJS framework. To use the $interval service, it is first needed to
4 min read