Open In App

How to access cookies in AngularJS?

Last Updated : 09 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

 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.

Steps to configure the AngularJS Application

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=
      </script>
    <script src=
      </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:

Cookie1

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=
    </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:

Cookie2



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads