Online Snippets Library

A Simple example of cookie in AngularJS

AngularJS provides ngCookies module and $cookieStore service to use Browser Cookies.

We need to add angular-cookies.min.js file to use cookie feature.

Method

get(key); // This method returns the value of given cookie key. getObject(key); //This method returns the deserialized value of given cookie key. getAll(); //This method returns a key value object with all the cookies. put(key, value, [options]); //This method sets a value for given cookie key. remove(key, [options]); //This method remove given cookie.

Example

HTML
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular-cookies.min.js"></script>
</head>
<body ng-controller="MyController">
{{cookiesUserName}} loves {{cookietechnology}}.
</body>
</html>
JavaScript
var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('MyController', ['$scope', '$cookies', '$cookieStore', '$window', function($scope, $cookies, $cookieStore, $window) {
$cookies.userName = 'Max Joe';
$scope.cookiesUserName = $cookies.userName;
$cookieStore.put('technology', 'Web');
$scope.cookietechnology = $cookieStore.get('technology'); }]);