user3811714
user3811714

Reputation: 276

How to get cookie in AngularJS

I need to read a cookie that is stored in Chrome using AngularJS,the cookie was created using javascript, when I try to get/read the cookie its says cannot read property get. Here is my script

if (!ngAppModule) {
    var ngAppModule = angular.module('myApp',['ngCookies']);
}

function UserSettings($http,$cookieStore ) {
    var self = this;
    self.$http = $http;
 self.GetCookie = function () {
       self.DepartmentId = $cookieStore.get('DepartmentId') ;
       console.log(self.DepartmentId);
    }
    self.GetCookie();
    self.SaveDepartmentID = function () {
        document.cookie = 'DepartmentId' + "=" + self.DepartmentId + "; " + "expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/";
        alert("DepartmentId Save.");
    }
}
ngAppModule.controller('DepartmentsController', ['$scope', '$http', function ($scope, $http,$cookieStore) {
    $scope.UserSettings = new UserSettings($http,$cookieStore);
}]);

Upvotes: 0

Views: 796

Answers (1)

Marc Harry
Marc Harry

Reputation: 2430

In your definition of the controller you have passed in $scope and $http but you haven't passed in the $cookieStore.

ngAppModule.controller('DepartmentsController', ['$scope', '$http', '$cookieStore', function ($scope, $http,$cookieStore) {
    $scope.UserSettings = new UserSettings($http,$cookieStore);
}]);

UPDATE

If you take a look at this codepen: http://codepen.io/anon/pen/bpyra. I have got it working in a small test. Hopefully this helps. I had to change the function that was being passed to the controller in order to get it working.

Upvotes: 1

Related Questions