ProgrammerGuide.Net | Step by Step Programmer Guide

Handling Cookies in AngularJS | Session Variables in AngularJS | Managing Sessions During Page Refresh in AngularJS | AngularJS Tutorial

The $cookieStore directive gives you read/write access the local cookie. You can store session-dependent information in the same way as the ASP session uses cookies.

In order to use $cookieStore directive, we need to include the below angular-cookies script tag:


<script src=”/Scripts/angular-cookies-1.0.0rc10.js” type=”text/javascript”></script>

Next, we need to register the ngCookies module with our app as given below:


var myApp = angular.module(“myApp”, ['ngCookies']);

Then we need to inject the $cookieStore service into the angularjs Controller. The below coding snippet shows an example of how the LogonController is constructed with $cookieStore:


myApp.controller(‘LogonController’, function ($scope, $http, $location, $cookieStore) {
    $cookieStore.put(‘loggedin’, ‘true’);
});

In the above example, once the user successfully logged in we create a cookie ‘loggedin’ and assign value ‘true’ to it.

This value will be stored as key-pair value in cookies. So We can get the value of loggedin from cookies as given below from $cookieStore:


$scope.loggedIn = $cookieStore.get(‘loggedin’)

Crack your interviews with AngularJS Interview Questions

Please click here for related products on Amazon!

Jayashee

Add comment

Want to Check Celebrities News?