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:
-
Include the
ngCookiesmodule: Include thengCookiesmodule in your AngularJS application module by adding'ngCookies'as a dependency:javascriptangular.module('myApp', ['ngCookies']) -
Use the
$cookiesservice: Inject the$cookiesservice into your controller or service to handle cookies:javascriptangular.module('myApp').controller('MyController', ['$cookies', function($cookies) { // Your logic code }]); -
Delete all cookies: Retrieve all cookies using
$cookies.getAll(), then iterate through each cookie and delete it using$cookies.remove(key):javascriptangular.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.