VOOZH about

URL: https://www.geeksforgeeks.org/angular-js/how-to-set-get-and-clear-cookies-in-angularjs/

⇱ How to set, get and clear cookies in AngularJS ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to set, get and clear cookies in AngularJS ?

Last Updated : 2 Aug, 2024

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.com/ajax/libs/angular.js/1.6.1/angular-cookies.js

We need to include $cookies in your controller and it has to Get, Set, and Clear method to get, set and clear cookies respectively. Angular has inbuilt directives named as ngCookies.

Writing Cookies: The WriteCookie function of the controller gets called When the Write Cookie Button is clicked. The WriteCookie function saves the input box value as cookies, using the $cookieStore service of the ngCookies module. The $cookieStore put function has two parameters:

  • Name (Key)
  • Value

Syntax:

$scope.SetCookies = function () {
$cookies.put("username", $scope.username);
};

Reading Cookies: The ReadCookie function of the controller gets called when the Read Cookie Button is clicked. The ReadCookie function fetches the value of the Cookie using the $cookieStore service of the ngCookies module. The $cookieStore get function has one parameter:

  • Name (Key)

Syntax:

$scope.GetCookies = function () {
$window.alert($cookies.get('username'));
};

Removing Cookies: The RemoveCookie function of the controller gets called when the Remove Cookie Button is clicked. The RemoveCookie function removes the Cookie using the $cookieStore service of the ngCookies module. The $cookieStore remove function has one parameter:

  • Name (Key)

Syntax:

$scope.ClearCookies = function () {
$cookies.remove('username');
};

Example: This example illustrates to set, get & clear cookies in AngularJS.

Output:

Comment

Explore