Add (Write), Read, Remove (Delete) Cookies in AngularJS Example

Last Reply on May 31, 2015 04:40 AM By Mudassar

Posted on Apr 29, 2015 03:23 AM

i already can get a cookie as the following. i call this cookie in my module and pass it as a parameter.how do i change the code to get a cookie in angular?

 

$(document).ready(function ()
{
Cookie();
});
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}

function Cookie()
{
var cookie = getCookie('Id');

}

function Module($http)
{
var self = this;
self.$http = $http;
self.CookieID = getCookie('Id');

self.test=function(){
var params = { testId:self.CookieID }
}
}

 

Posted on May 31, 2015 04:40 AM

Here's an example to Write, Read and Remove cookies.

<html>
<head>
    <title></title>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
    </style>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-cookies.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', ['ngCookies']);
        app.controller('MyController', function ($scope, $window, $cookieStore) {
            $scope.WriteCookie = function () {
                $cookieStore.put("Name", $scope.Name);
            };
            $scope.ReadCookie = function () {
                $window.alert($cookieStore.get('Name'));
            };
            $scope.RemoveCookie = function () {
                $cookieStore.remove('Name');
            };
        });
    </script>
    <div ng-app="MyApp" ng-controller="MyController">
        Name:
        <input type="text" ng-model="Name" />
        <br />
        <br />
        <input type="button" value="Write Cookie" ng-click="WriteCookie()" />
        <input type="button" value="Read Cookie" ng-click="ReadCookie()" />
        <input type="button" value="Remove Cookie" ng-click="RemoveCookie()" />
    </div>
</body>
</html>

Demo