In this article I will explain how to use Browser Cookies in AngularJS i.e. reading values stored in Cookies, writing (saving) values in Cookies and also how to delete Cookies using AngularJS.
AngularJS uses ngCookies module and $cookieStoreservice to carry out the various functions of reading, writing and removing Cookies.
AngularJS Cookies: Read, Write (Save) and Remove (Delete) Cookies
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
Along with the AngularJS JavaScript file, angular-cookies.js file also needs to be inherited in order to perform operations on Browser Cookies.
The following AngularJS App makes use of ngCookies module and $cookieStore service.
The AngularJS app HTML DIV consists of an HTML TextBox set with ng-model directive and three Buttons set with ng-click directive.
Writing Cookies
When the Write Cookie Button is clicked, the WriteCookie function of the controller gets called which saves the value of the TextBox to a Cookie using the $cookieStore service of the ngCookies module.
The $cookieStore put function has two parameters, first the Name (Key) of the Cookie and second the Value to be stored in the Cookie.
Reading Cookies
When the Read Cookie Button is clicked, the ReadCookie function of the controller gets called which fetches the value of the Cookie using the $cookieStore service of the ngCookies module.
The $cookieStore get function accepts the Name (Key) of the Cookie in order to read its value.
The value read from the Cookie is displayed using JavaScript Alert Message Box.
Removing Cookies
When the Remove Cookie Button is clicked, the RemoveCookie function of the controller gets called which removes the Cookie using the $cookieStore service of the ngCookies module.
The $cookieStore remove function accepts the Name (Key) of the Cookie in order to remove the Cookie.
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-cookies.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', ['ngCookies']);
app.controller('MyController', function ($scope, $window, $cookieStore) {
$scope.WriteCookie = function () {
$cookieStore.put("Name", $scope.Name);
};
$scope.ReadCookie = function () {
$window.alert($cookieStore.get('Name'));
};
$scope.RemoveCookie = function () {
$cookieStore.remove('Name');
};
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
Name:
<input type="text" ng-model="Name" />
<br />
<br />
<input type="button" value="Write Cookie" ng-click="WriteCookie()" />
<input type="button" value="Read Cookie" ng-click="ReadCookie()" />
<input type="button" value="Remove Cookie" ng-click="RemoveCookie()" />
</div>
</body>
</html>
Screenshot
Demo
Downloads