0

I am trying to retrieve values from localStorage and bind them to a checkbox in my Angular app.

//controller code
var storage = window.localStorage;  
$scope.Setting = storage.getItem('setting');


//view
<div>{{Setting}}</div>
<input type="checkbox"    ng-model="Setting">  

In the above code the div will correctly show true or false, however this is not bound to the checkbox. If the code is changed to $scope.Setting = true; this will work, is Angular attempting to bind the model to the checkbox before it has been retrieved from localstorage?

1 Answer 1

4

The problem is when you save data to local storage everything is converted into string so boolean comparison fails. Your option are convert the data back to json format or in your case since it is just a boolean value you can also use $scope.$eval

$scope.Setting = $scope.$eval(storage.getItem('setting'));

See this fiddle http://jsfiddle.net/cmyworld/Jn7N2/

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that worked a charm. How about doing the reverse and storing the value of the checkbox in storage? If I add an ng-onchange to the checkbox and try store the value in localstorage it is always true.
See my updated fiddle. You need to explicitly set the storage value there is no data biding with storage

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.