slevin
slevin

Reputation: 3896

value of factory gets erased after page refresh

So this is my factory

app.factory('userFactory', function(localStorageService, $http, $rootScope) {       
    var myUser = {};    

    myUser.isCrazy = false;
    return myUser;
});

When user logs in, in the login controller I get some data from the db and decide , using an if/else , if the user is crazy or not, so I have

  app.controller('loginController', ['$scope', 'localStorageService', '$location','userFactory','$rootScope',
  function ($scope, localStorageService, $location, userFactory, $rootScope ) {  
      userFactory.isCrazy = true;
        }
  ]); 

and then, in another page's controller I show/hide divs , according to the userFactory.isCrazy (also true/false).

app.controller('anotherPageController' ,['$scope', '$filter', '$rootScope', 'userFactory','localStorageService',
        function ($scope, $filter, $rootScope, userFactory, localStorageService) {  

        if(userFactory.isCrazy == true){    
                    $scope.myMessage = true;
        } 

         }
     ]); 

The html of $scope.myMessage is

<div ng-hide="myMessage">

Here is my problem.

After the login, isCrazy gets true. When I first visit the page, according to the anotherPageController, the message is hidden, isCrazy is still true. All good.

If I hit refresh, isCrazy goes back to false and the message is no longer hidden.

What am I missing here? Why isCrazy is not keeping its value?

Thanks

Upvotes: 0

Views: 62

Answers (2)

gabriel garcia
gabriel garcia

Reputation: 367

Just create a cookie with that value. Search the setCookie API. You can do it with JavaScript or PHP, as you wish. If you still want to do it with angular js, check the angular-js cookie API .

Upvotes: 1

Oleksandr Pastukhov
Oleksandr Pastukhov

Reputation: 21

Yes it is not save the value. For that you have to use at least local- or session storage to keep these values.

Upvotes: 1

Related Questions