19
DecUnderstanding cookies in AngularJS
AngularJS provides ngCookies
module for reading and writing browser cookies. To use it include the angular-cookies.js
file and set ngCookies as a dependency in your angular app. This module provides two services for cookie management: $cookies and $cookieStore.
$cookies
This service provides read/write access to browser's cookies. If you want to use existing cookie solution, say read/write cookies from your existing server session system then use $cookie.
<script> var app=angular.module('cookiesExample', ['ngCookies']); app.controller('ExampleController', ['$cookies', function ($cookies) { // Retrieving a cookie var favoriteCookie = $cookies.myFavorite; // Setting a cookie $cookies.myFavorite = 'oatmeal'; }]); </script>
$cookiesStore
$cookieStore is a thin wrapper around $cookies. It provides a key-value (string-object) storage that is backed by session cookies. The objects which are put or retrieved from this storage are automatically serialized or deserialized by angular to JSON and vice versa.
If you are creating a new solution which will persist cookies based on key/value pairs, use $cookieStore.
<script> var app=angular.module('cookieStoreExample', ['ngCookies']); app.controller('ExampleController', ['$cookieStore', function ($cookieStore) { // Put cookie $cookieStore.put('myFavorite', 'oatmeal'); // Get cookie var favoriteCookie = $cookieStore.get('myFavorite'); // Removing a cookie $cookieStore.remove('myFavorite'); }]); </script>
What do you think?
I hope you will enjoy the cookies in AngularJS while developing your app with AngularJS. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.
Take our free skill tests to evaluate your skill!

In less than 5 minutes, with our skill test, you can identify your knowledge gaps and strengths.