How to use Cookies in AngularJS
Using cookies in AngularJS is pretty simple. We can store the information in AngularJS cookies and we can retrieve it whenever required.
Things to remember when using AngularJS cookies are,
- We need to include angular-cookies.js file from external source or internally
- We need to inject ngCookies module in app definition
- We need to use $cookies as the parameter for controller function (Note: The $cookieStore service is deprecated. Please use the $cookies service instead.)
- We have to use put and get methods to use cookies
- We need to specify folder path when storing and removing cookies.
Now, we are going to see an example.
<html> <head> <title>Angular JS Cookie Implementation</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular-cookies.js"></script> </head> <body ng-app="cookieApp"> <div ng-controller="cookieController"> <p>{{ msg }}</p> <input type="text" ng-model="mycookie" /> <input type="submit" ng-click="add_user_cookie()" value="Add to Cookie"/> <p>Cookie value : {{ cookie_val }}</p> <p ng-click="remove()" style="cursor:pointer;color:blue;" ng-show="isCookieSet"><u>Remove Cookie</u></p> </div> <script> var app = angular.module("cookieApp",['ngCookies']); app.controller("cookieController",function($scope,$cookies){ $scope.mycookie = "India"; $scope.add_user_cookie = function(){ if($scope.mycookie != ""){ $scope.msg = ""; $cookies.put('myFavorite', $scope.mycookie,{path:'/'}); $scope.cookie_val = $cookies.get('myFavorite'); $scope.mycookie = ""; $scope.isCookieSet = true; } else{ $scope.msg = "Enter some text.."; } }; $scope.remove = function(){ $cookies.remove("myFavorite",{path:'/'}); $scope.cookie_val = $cookies.get('myFavorite'); $scope.msg = "Cookie removed.."; $scope.isCookieSet = false; }; }); </script> </body> </html>
var app = angular.module("cookieApp",['ngCookies']);
We are injecting ‘ngCookies’ modules to the app
app.controller("cookieController",function($scope,$cookies){
We are passing $cookies as parameter to the controller function
$cookies.put('myFavorite', $scope.mycookie,{path:'/'});
This method adds data to the cookie named “myFavorite” at the specified path.
$scope.cookie_val = $cookies.get('myFavorite');
This method gets the cookie value and assign it to the cookie_val variable
$cookies.remove("myFavorite",{path:'/'});
This method removes the cookie value.
Thanks for reading.
Feedback are welcome. Please feel free to ask questions.
Don’t forget to subscribe to Geeks.Gallery, to get free emails to your inbox.
Related Posts
Nagarajan
View Nagarajan's Profile
Latest posts by Nagarajan (see all)
- Random Image viewer using AngularJS - June 30, 2016
- Building your first AngularJS app – Shopping list - June 22, 2016
- How to use Cookies in AngularJS - October 20, 2015