Using Cookies in AngularJS

Angular provides ngCookies module to manipulate browser cookies, cookies can be helpful when it comes to persisting data between sessions, they are also stored on the client side so each user can have their unique set of cookies. It sounds like a good place to store non-sensitive data which is specific to the user.

Getting ngCookies module - 

ngCookies is not included in core AngularJS, but we can grab it from the angular site.  ‚Äč

Note: you can get angular cookie module from CDN, it should look like this, just change "1.4.2" with the current version.

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

Building a custom navigation bar theme selector

Let's create navigation bar with two theme options, 'Dark' and 'Light', we will change the theme of navigation bar when user clicks those options accordingly,  We are also going to save information in cookie so next time when user loads the page he gets the previously selected theme, same thing can be done using HTML5 Local Storage, check out our HTML5 Local storage tutorial.

HTML

 <!doctype html>
<html ng-app="app">
  <head>
    <title>Cookies in angular js</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body ng-controller="NavigationController">
      <nav class="navbar" change-navbar-theme><!-- Directive for chaning navigation theme -->
          <div class="container-fluid">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#main-navigation">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" href="#">ngCookies</a>
            </div>

            <div class="collapse navbar-collapse" id="main-navigation">
              <ul class="nav navbar-nav navbar-right">
                
                <!-- click events for changing theme -->
                <li><a href ng-click="changeTheme('inverse')">Dark Theme</a></li>
                <li><a href ng-click="changeTheme('default')">Light Theme</a></li>
              </ul>
            </div>
          </div>
      </nav>


      <!-- Core angular -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
      
      <!-- ngCookies -->

      <script src="https://code.angularjs.org/1.3.9/angular-cookies.min.js"></script>
 
       <!-- our script -->
      <script src="app.js"></script>
  </body>
</html>

JavaScript(AngularJS)

var app = angular.module('app', ['ngCookies']);

app.controller('NavigationController', function($scope, $cookieStore) {

  // Initializing default theme, if cookie "navbar-theme" is not defined, we will load default theme
  $scope.theme = (typeof $cookieStore.get('navbar-theme') !== "undefined") ? $cookieStore.get('navbar-theme') :  'default';

//changing theme value when user selects new theme
//Also setting cookie navbar-theme value with user selected theme

  $scope.changeTheme = function(themeName) {
      $scope.theme= themeName;
      $cookieStore.put('navbar-theme', themeName);
  };

});


app.directive('changeNavbarTheme', function() {
  return {
    link : function(scope, element, attrs) {

        function change(newValue, oldValue, el)
        {
          //when page loads oldValue and newValue will be same so no need to remove Class
          if(newValue !== oldValue)
          {
            element.addClass('navbar-'+newValue ).removeClass('navbar-' +oldValue);
            return;
          }
          element.addClass('navbar-'+newValue);

        }

        //creating watcher for theme
        // this will run when theme variable on scope changes 
        scope.$watch('theme', function(newValue, oldValue) {
                //function to change theme
                change(newValue, oldValue, element);
        });
    }
  };
});

We are using $cookieStore  to get or put cookie.

To get cookies, we can use get function from $cookieStore object  which only needs one argument, cookie name. 

$cookieStore.get('navbar-theme')

To put cookie, we use put function, the first argument will be cookie name and second will be the value ( it can store the object as well ).

 $cookieStore.put('navbar-theme', themeName);

That's it, there is one small problem, cookies can co-exist with the same name on each page of the website,  right now there is no way to put cookie base path in default ngCookies module, so if you get undefined cookie value on different page put base URL to your head tag.

<base href="/">

Now every cookie will have "/" as their path, there is another package "angular-cookie" which lets you set cookie path:

https://github.com/ivpusic/angular-cookie

 

Something to say? Tell us in comment section.