AngularJS $cookies are not persisting
angularjs, cookies, javascript
Solution
In Angular v1.4 you can finally set some options for the cookies. Here's a very simple example:
var now = new $window.Date(),
// this will set the expiration to 6 months
exp = new $window.Date(now.getFullYear(), now.getMonth()+6, now.getDate());
$cookies.put('yourCookie','blabla',{
expires: exp
});
var cookie = $cookies.get('yourCookie');
console.log(cookie); // logs 'blabla'
If you check your cookies after running this code you will see that the expiration will be properly set to the cookie named `yourCookie`.
The object passed as a third param to the `put` function above allows for other options as well, such as setting `path`, `domain` and `secure`. Check the docs for an overview.
Problem
I have a login form with a remember username function. All they do is check the box and the cookie is saved via: ``` $scope.toggleCookie = function() { //-- $scope.remember is the model for the checkbox $cookieStore.put('remember', $scope.remember); if (!$scope.remember) $cookieStore.remove('email'); } ``` When the user returns to the login page, first I check the `remember` cookie: ``` $scope.remember = ($cookieStore.get('remember') == null || $cookieStore.get('remember') == false) ? false : true; ``` Then I check if there is a value in the `email` cookie: ``` $scope.email = ($cookieStore.get('email') != null) ? $cookieStore.get('email') : ''; ``` Now all the above is working fine, I can login with it checked, logout and I can see my username in the input field. If I uncheck it, login and logout, the username is gone. I can also see this happening in the resources->cookies tab in the chrome dev tools. I can refresh the page and still, the username is there when checked. My issue is that when I CLOSE chrome, reopen it, all the cookie data is gone. Why is this? I don't have much experience with cookies to begin with.