How can someone set, get, and clear cookies in AngularJS?

AngularJS has a module known as ngCookies. Before we inject ngCookies, we should include angular-cookies.js into the application.

  • Set Cookies
    We can use the put method to set cookies in a key-value format.
    $cookies.put(“username”, $scope.username);
  • Get Cookies
    We can use the get method to get cookies.
    $cookies.get(‘username’);
  • Clear Cookies
    We can use the remove method to remove or clear cookies.
    $cookies.remove(‘username’)

In AngularJS, you can use the $cookies service to set, get, and clear cookies. Here’s how you can perform these operations:

  1. Setting a Cookie: To set a cookie, you can use the $cookies service to store key-value pairs. Here’s an example:
    javascript

 

  • angular.module('myApp', ['ngCookies'])
    .controller('MyController', function($cookies) {
    $cookies.put('myCookieKey', 'cookieValue');
    });

    In this example, the put method is used to set a cookie with the key 'myCookieKey' and the value 'cookieValue'.

  • Getting a Cookie: To retrieve the value of a cookie, you can use the $cookies service again. Here’s an example:
    javascript
  • angular.module('myApp', ['ngCookies'])
    .controller('MyController', function($cookies) {
    var cookieValue = $cookies.get('myCookieKey');
    console.log(cookieValue);
    });

    In this example, the get method is used to retrieve the value of the cookie with the key 'myCookieKey'.

  • Clearing a Cookie: To clear a cookie, you can use the $cookies service with the remove method. Here’s an example:
    javascript

 

  1. angular.module('myApp', ['ngCookies'])
    .controller('MyController', function($cookies) {
    $cookies.remove('myCookieKey');
    });

    In this example, the remove method is used to delete the cookie with the key 'myCookieKey'.

Remember to include the ‘ngCookies’ module as a dependency in your AngularJS application to use the $cookies service.