How to access cookies in AngularJS?
Last Updated :
26 Jul, 2024
AngularJS is the most useful framework for developing dynamic web applications. While developing the applications, we need to store and access the cookies for many other functionalities like retiring the user details, etc. Cookies are nothing but the data that is usually stored in the client's browser. These cookies can also be used for maintaining the user's sessions, tracking the user preferences, and also for other functional work. In this article, we will see how we can access the cookies in AngularJS with different approaches. We will see the practical implementation along with the example.
The below steps will be followed for configuring the AngularJS Application:
- Create a new folder for the project. We are using the VSCode IDE to execute the command in the integrated terminal of VSCode.
mkdir access-cookies
cd access-cookies
- Create the index.html file in the newly created folder, we will have all our logic and styling code in this file. We can also create separate files for HTML, CSS, and JS.
We will understand the above concept with the help of suitable approaches & will understand its implementation through the illustration.
Accessing Cookies using a Custom Service
In this approach, we are accessing the cookie in AngularJS using the Custom Service. We have specified simple UI components to set the new cookie value, and also update and access the cookie values. The 'CookieService' service mainly handles the cookie functions. When the 'Set Cookie' button is clicked, it updates the cookie value in the client browser, and by using the 'Access Cookie' button, the cookie value is been retrieved and displayed to the user in terms of an alert message.
Example: Below is an example that showcases how to access cookies in AngularJS using Custom Service.
HTML
<!DOCTYPE html>
<html ng-app="cookieApp">
<head>
<title>Cookie Access</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.js">
</script>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/angular-cookies/1.8.3/angular-cookies.min.js">
</script>
<style>
h1 {
color: green;
text-align: center;
}
.container {
background-color: #f5f5f5;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
margin: 20px auto;
max-width: 400px;
padding: 20px;
}
label {
display: block;
font-weight: bold;
margin-bottom: 5px;
}
input[type="text"] {
width: 100%;
padding: 8px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 3px;
}
.button-container {
display: flex;
flex-direction: column;
align-items: center;
}
button {
background-color: #4CAF50;
border: none;
color: white;
padding: 10px 20px;
cursor: pointer;
border-radius: 3px;
width: 100%;
margin-bottom: 10px;
}
button:hover {
background-color: #45a049;
}
.cookie-value {
font-weight: bold;
text-align: center;
margin-top: 15px;
font-size: 18px;
}
</style>
</head>
<body ng-controller="CookieController">
<h1>GeeksforGeeks</h1>
<div class="container">
<h3>Approach 1: Using a Custom Service</h3>
<label for="newCookie">Enter Cookie Value:</label>
<input type="text"
id="newCookie"
ng-model="newCookie"
placeholder="Cookie Value">
<div class="button-container">
<button ng-click="setCookie()">
Set Cookie
</button>
<button ng-click="showCookie()">
Access Cookie
</button>
</div>
<div class="cookie-value">
Current Cookie Value: {{ cookieValue }}
</div>
</div>
<script>
angular.module('cookieApp', ['ngCookies'])
.service('CookieService', ['$cookies', function ($cookies) {
this.getCookieValue = function () {
return $cookies.get('cookieValue') || 'Default Cookie';
};
this.setCookieValue = function (newCookie) {
$cookies.put('cookieValue', newCookie);
};
}])
.controller('CookieController', ['$scope', 'CookieService',
function ($scope, CookieService) {
$scope.cookieValue = CookieService.getCookieValue();
$scope.setCookie = function () {
if ($scope.newCookie) {
CookieService.setCookieValue($scope.newCookie);
$scope.cookieValue = $scope.newCookie;
$scope.newCookie = '';
}
};
$scope.showCookie = function () {
alert('Cookie Value: ' + $scope.cookieValue);
};
}]);
</script>
</body>
</html>
Output:
Accessing Cookies using JavaScript's document.cookie
In this approach, for accessing the cookie in AngularJS, we are using the JavaScript's document.cookie method. When the 'Set Cooie' button is clicked, it creates a sample cookie with the value "Hello Geek!" which has an expiry of 1 hour. After clicking on the "Get Cookie" button. the value is been displayed to the user. Here, the 'cookieConteoller' is used to overall handle the logic of setting and getting the cookie value. Using the 'document.cookie' property, we are retrieving and displaying the cookie value to the user.
Example: Below is an example that showcases how to access cookies in AngularJS using a document.cookie
HTML
<!DOCTYPE html>
<html ng-app="cookieApp">
<head>
<meta charset="UTF-8">
<title>
AngularJS Cookies Example - Approach 2
</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f7f7f7;
margin: 0;
padding: 0;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
border-radius: 5px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
}
h1 {
color: green;
}
h3 {
color: #333;
}
button {
background-color: #FF5722;
color: #fff;
border: none;
padding: 10px 20px;
cursor: pointer;
}
button:hover {
background-color: #FF7043;
}
p {
font-size: 18px;
margin-top: 10px;
}
</style>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</script>
</head>
<body ng-controller="cookieController"
style="text-align: center;">
<div class="container">
<h1>GeeksforGeeks</h1>
<h3>
Approach 2: Using JavaScript's document.cookie
</h3>
<button ng-click="setCookie()">
Set Cookie
</button>
<button ng-click="getCookie()">
Get Cookie
</button>
<p>Cookie Value: {{ cookieValue }}</p>
</div>
<script>
var app = angular.module('cookieApp', []);
app.controller('cookieController', function ($scope) {
$scope.cookieValue = '';
$scope.setCookie = function () {
var cookieName = 'exampleCookie';
var cookieValue = 'Hello, Geek!';
var expirationDate = new Date();
expirationDate.setHours(expirationDate.getHours() + 1);
document.cookie = cookieName + '=' + cookieValue +
';expires=' + expirationDate.toUTCString();
};
$scope.getCookie = function () {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
if (cookie.startsWith('exampleCookie=')) {
$scope.cookieValue =
cookie.substring('exampleCookie='.length,
cookie.length);
break;
}
}
};
});
</script>
</body>
</html>
Output:
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
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 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