0

I have the code snippet below inside of my controller. In my HTML, I have a checkbox with ng-checked="enterToSend" attached to it. As well as an ng-click="enterToSendCheck()"

$scope.enterToSend = localStorage.getItem('enterToSend');

$scope.enterToSendCheck = function() {
    $scope.enterToSend = ($scope.enterToSend == false) ? true : false;

    localStorage.setItem('enterToSend', $scope.enterToSend);
}

It's updating properly in localstorage. I open up localstorage, check it on/off and it updates to true/false in my browser.

However, when loading the page, using ng-checked or the regular checked attribute, it's checked (whether true or false). Why is this?

1 Answers1

3

localStorage stores string representations only and "true" or "false" is not the same as true or false.

$scope.enterToSend = booleanFromString(localStorage.getItem('enterToSend'));


function booleanFromString(s) {
    if (s == 'true') return true;
    if (s == 'false') return false;

    throw new Error("Unable to convert '" + s + "' to a boolean, valid arguments are 'true' or 'false'");
}
plalx
  • 42,889
  • 6
  • 74
  • 90