문제

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].

도움이 되었습니까?

해결책

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.

다른 팁

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"
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top