Understanding cookies in AngularJS

29 dec. 2023
Intermediate
42,8K Views
1 min read  

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. Exploring dedicated Angular JS Training can provide comprehensive guidance on utilizing ngCookies and other essential modules effectively within AngularJS applications.

$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. For those looking to gain a deeper understanding of utilizing cookies and other essential features in AngularJS applications, consider exploring an Angular certification Training program

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Learn to Crack Your Technical Interview

Accept cookies & close this