Jose
Jose

Reputation: 19

Get jquery cookie using angular

I'm using jquery.cookie v1.4.1 to set a cookie like this

$.cookie('userCookie', $("#user").val());

Where $("#user").val() is returning something like 'username'

Then in an angular app, am trying to retrieve this cookie using

var userCookie = $cookies.get('userCookie');

But is not working, I'm getting:

var userCookie = undefined

I'm using AngularJS v1.4.8 with corresponding ngCookies

Any help would be nice....

Upvotes: 0

Views: 597

Answers (2)

Jose
Jose

Reputation: 19

Thanks to charlietfl I got it to work.

It happens that I was setting the cookie for a specific path, let say '/domain/somepath' and then I was trying to retrieve it from '/domain/someotherpath', where the cookie was not available.

I fix it specifying the path on the cookie to all my domain like this:

 $.cookie('userCookie',$("#user").val(), { path: '/' });

Upvotes: 1

Eigi
Eigi

Reputation: 716

Why don't you use angular to store your cookies?

$cookies.put('userCookie', $("#user").val());

Btw: its horrible if you use JQuery like this inside your Angular App.

$cookies.get('userCookie');

Your problem maybe: the cookie will be created BEFORE your DOM-Element is even rendered on the page. Try $.cookie('userCookie', 'test123'); , this should work pretty sure (with angular 100%).

How to fix this? First of all, DONT USE JQUERY LIKE THIS IF YOU HAVE ANGULAR!!!

<input ng-model="username"></input>

$cookies.put('userCookie', $scope.username);

Upvotes: 0

Related Questions