Pergunta

My code does a check like this:

if (localStorage.isAuthenticated == true) {
   $scope.template = $scope.templates[1];
} else {
   $scope.template = $scope.templates[0];
}

Can someone tell me if this is valid. If not then how can I set it to true or false?

Also how can I check if localStorage.isAuthenticated is not set. In that case I want the setting to be $scope.templates[1].

Foi útil?

Solução

Just use JSON.parse:

localStorage.isAuthenticated = true;

if (localStorage.isAuthenticated && JSON.parse(localStorage.isAuthenticated )) {
   //great
}

I use the && to check if the value is undefined. If localStorage.isAuthenticated returns undefined because it's not set, you get a false back.

Outras dicas

No, you cant

because localstorage supports only string, not boolean
you can check this link http://www.acetous.de/152/localstorage-sessionstorage-arrays-und-objekte-speichern

UPDATE:

 if(localStorage.getItem("key")==null) 
         localStorage.setItem("key","true");
 console.log(localStorage.getItem("key"));//return "true"
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top