Objectives and outcomes

In this tutorial we are going to learn about angular-js ngCookies module. We can link the module to our application using dependency injection. This modules help in reading and writing browser cookies.

ngCookies
Image source: (https://docs.angularjs.org/api/ngCookies)

For ngCookies module to work we need to include angular-cookies.js file in our application. We can link the file using four ways:



If you have downloaded angular package on localhost

<script src="angular-1.4.6/angular-cookies.js"></script>


Using CDN

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-cookies.js"></script>


Using npm

npm install angular-cookies@1.4.6


Using bower

bower install angular-cookies@1.4.6


HTML code:

<html>
<head>
<title>AngularJS Cookies</title>
<meta charset="utf-8">
<script src="angular-1.4.6/angular.min.js"></script>
<script src="angular-1.4.6/angular-cookies.js"></script>
</head>
<body>
<div ng-app="cookie_app" ng-controller="cookie_control">
<p>Website: <b>{{site}}</b><br/>
Technology: <b>{{tech}}</b><br/>
Topic: <b>{{tutorial}}</b></p>
</div>
</body>
</html>


Javascript

<script>
var app = angular.module('cookie_app', ['ngCookies']);
app.controller('cookie_control', ['$scope', '$cookies', '$cookieStore', function($scope, $cookies, $cookieStore) 
{
$cookies.sitename = "codeshot.in";
$scope.site = $cookies.sitename;
$cookieStore.put('category', 'AngularJS');
$cookieStore.put('topic', 'Cookies in AngularJS');
$scope.tech = $cookieStore.get('category');
$scope.tutorial = $cookieStore.get('topic');
}]);
</script>


Below is the example for $cookies and $cookieStore


Website: {{site}}
Technology: {{tech}}
Topic: {{tutorial}}


$cookieStore has two functions get() and put() associated with it. Both uses the key-value pair to handle the data.