AngularJS — Cookies
Setup Cookies
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-cookies.min.js"></script>
var app = angular.module('myApp', ['ngCookies']);
Using Cookies
app.controller('CookieController', function($scope, $cookies) {
// Set cookie
$cookies.put('username', 'john');
$cookies.put('preferences', JSON.stringify({ theme: 'dark' }));
// Get cookie
var username = $cookies.get('username');
// Remove cookie
$cookies.remove('username');
// Get all cookies
var allCookies = $cookies.getAll();
});
Cookie Options
$cookies.put('token', 'abc123', {
expires: 'Thu, 01 Jan 2025 00:00:00 GMT',
path: '/',
secure: true
});
Session Management
app.factory('AuthService', function($cookies) {
return {
login: function(user) {
$cookies.put('token', user.token);
$cookies.put('user', JSON.stringify(user));
},
logout: function() {
$cookies.remove('token');
$cookies.remove('user');
},
getUser: function() {
return JSON.parse($cookies.get('user') || '{}');
}
};
});
Mini Practice
- Set and get cookies
- Remove cookies
- Implement session management
- Store user preferences
Up Next
Continue with Security — AngularJS security.
Related Topics
Frequently Asked Questions about Cookies
What is Cookies in AngularJS?
Cookies is a fundamental concept in AngularJS. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Cookies?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Cookies.
Why is Cookies important in AngularJS?
Cookies is essential for AngularJS development. Understanding this concept will help you write better code and solve real-world problems more effectively.