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 determine active route in AngularJS ?
In this article, we will see how to determine the active route in AngularJS, along with understanding the basic implementation through the example. Approach: To determine which is the active route at any moment in AngularJS this can be achieved by using $on() & $location.path() method. An event
2 min read
How to Clear Cookies on Android?
Cookies are small files that your browser stores for the purpose of recording certain interactions within the web or personalizing your navigation experience. Although some cookies remain useful for saving logins or website preferences, others may bog down your device or become an invasion of your p
5 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 use *ngIf else in AngularJS ?
Introduction: The ngIf directive is used to show or hide parts of an angular application. It can be added to any tags, it is a normal HTML tag, template, or selectors. It is a structural directive meaning that it includes templates based on a condition constrained to boolean. When the expression eva
3 min read
How to detect a route change in AngularJS ?
In this article, we will see how to detect a route change in AngularJS. In order to detect route change at any moment in AngularJS, this can be achieved by using the $on() method. The $on() method is an event handler, the event which will handle $routeChangeSuccess which gets triggered when route/vi
2 min read
How to use bootstrap 4 in angular 2?
Bootstrap is an open-source toolkit for developing with HTML, CSS, and JS. The Bootstrap framework can be used together with modern JavaScript web & mobile frameworks like Angular. Bootstrap 4 is the newest version of Bootstrap, which is the most popular HTML, CSS, and JavaScript framework. This
2 min read
How to access the value of a Promise in AngularJS ?
AngularJS is one of the JS frameworks that consists of promises that are used to handle asynchronous tasks. In some scenarios, we need to handle the promise values by accessing them in the application. So, this can be done using the .then() method and also by using the callbacks in AngularJS. In thi
4 min read
How to implement history.back() in AngularJS?
Angular JS is a typescript-based web application framework. It is supported by the Angular team of Google and open-source developers. It is a component-based framework allowing the developers to reuse the components created. It is well-suited for large and complex applications because of its well-de
3 min read
How to Handle Anchor Hash Linking in AngularJS ?
AngularJS Anchor Hash Linking consists of developing a proper and efficient navigation experience in the one-page application. This feature of AngularJS enables users and developers to properly and smoothly scroll to specific sections of a webpage just by clicking on the navigation links, rather tha
6 min read