乐闻世界logo
搜索文章和话题

How to remove all cookies in Angularjs?

1个答案

1

Deleting all cookies in AngularJS can be achieved by using the $cookies service. First, ensure that the ngCookies module is included in your AngularJS application module. This is the official AngularJS module for handling cookies.

Here is a clear step-by-step example demonstrating how to delete all cookies:

  1. Include the ngCookies module: Include the ngCookies module in your AngularJS application module by adding 'ngCookies' as a dependency:

    javascript
    angular.module('myApp', ['ngCookies'])
  2. Use the $cookies service: Inject the $cookies service into your controller or service to handle cookies:

    javascript
    angular.module('myApp').controller('MyController', ['$cookies', function($cookies) { // Your logic code }]);
  3. Delete all cookies: Retrieve all cookies using $cookies.getAll(), then iterate through each cookie and delete it using $cookies.remove(key):

    javascript
    angular.module('myApp').controller('MyController', ['$cookies', function($cookies) { var allCookies = $cookies.getAll(); angular.forEach(allCookies, function (value, key) { $cookies.remove(key); }); }]);

In this example, we first retrieve all cookies using $cookies.getAll(), then use angular.forEach to loop through each cookie and delete it using $cookies.remove(key).

This method is highly effective for clearing all cookies stored in the user's browser, such as when logging out of the application to clear session information.

2024年8月12日 14:11 回复

你的答案