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
How to set, get and clear cookies in AngularJS ? In this article, we will see how to set, get & clear the Cookies in AngularJS, along with understanding the basic usage through the implementation. In AngularJS, we need to use angular-cookies.js to set, get and clear the cookies. You can use the live CDN link for this: https://cdnjs.cloudflare.
2 min read
How to Access HTTP Cookie in Node.js ? Cookies are small pieces of data sent by a server and stored on the client side, typically in the user's browser. They are often used to maintain stateful information such as user sessions, preferences, or tracking data. In Node.js, accessing and managing cookies is a common requirement for building
3 min read
How to allow access outside localhost in AngularJS ? In this article, we will see how to allow access outside the localhost in AngularJS, along with knowing the basic implementation through the example. Firstly, we will discuss how we can build an Angular application, run it, and preview it in the browser. We can easily do this using the CLI, provided
4 min read
How to access the Scope from outside JS Function in AngularJS ? In the AngularJS application, we generally need to access the scope from the outside JS function. This can be done using the global scope object like $rootScope or the AngularJS services. Accessing the scope from the outside of JS functions is to enable the manipulation of data in the scope of the a
4 min read
How to Clear all Cookies using JavaScript? Cookies allow clients and servers to exchange information via HTTP, enabling state management despite HTTP being a stateless protocol. When a server sends a response, it can pass data to the user's browser in the form of key-value pairs, which the browser stores as cookies. On subsequent requests to
2 min read
How to execute a routing in the AngularJS framework ? In this article, we will learn about how we can perform routing in AngularJS, along with understanding its implementation through the code example. Â Routing in AngularJS helps to develop Single Page Applications, which is a web app that loads only a single page, and the part of the page instead of t
6 min read
Introduction to AngularJS AngularJS is a popular open-source framework that simplifies web development by creating interactive single-page applications (SPAs). Unlike traditional websites that load new pages for each click, SPAs offer a smoother user experience by updating content on the same page. AngularJS makes this possi
4 min read
How to Remove a Cookie in PHP? Cookies are small text files stored in a user's browser. It contain data such as user preferences, session information, and other relevant details. PHP cookies are used to store information that can persist across different web pages or sessions. At times, you may need to delete or remove a cookie,
4 min read
Cypress - getCookies() Method Cookies play an essential role in web applications, storing user sessions, preferences, and other critical data. When performing automated testing with Cypress, it's often necessary to interact with cookies to validate their existence, values, and properties. The getCookies() method in Cypress allow
4 min read