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=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js">
</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=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js">
</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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Decorators in Python In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read