Trying to create an app, with a toggle setting that should be saved to local storage, haven't gotten much luck with it, though.
I'm using Ionic + Angular.JS
Here's my code, I'm getting the error Uncaught TypeError: Cannot assign to read only property
Controller.js:
.controller("ExampleController", ['$scope', '$window', function($scope, $window) {
$scope.CONFIG = localStorage.getItem('CONFIG');
if (!$scope.CONFIG) {
$scope.CONFIG = {karton: true};
}
$scope.save = function(checked) {
$scope.CONFIG.karton = checked;
localStorage.setItem('CONFIG', $scope.CONFIG);
}
}]);
the HTML file:
<div class="item item-avatar item-icon-right">
<img src="img/box.jpg">
<ion-toggle type="checkbox" ng-model="karton.checked" ng-change="save(karton.checked)" ng-init="karton.checked = CONFIG.karton" toggle-class="toggle-balanced" id="karton" name="karton">Karton</ion-toggle>
<div>Box Value: <span class="val">{{karton }}</span></div>
</div>
EDIT
I now have this but it returns an "undefined" in the console log:
.controller("ExampleController", ['$scope', '$window', function($scope, $window) {
$scope.CONFIG = (localStorage.getItem('CONFIG'));
if (!$scope.CONFIG) {
$scope.CONFIG = {karton: true};
}
$scope.save = function(checked) {
JSON.stringify($scope.CONFIG.karton) === checked;
localStorage.setItem('CONFIG', JSON.stringify($scope.CONFIG));
console.log(JSON.stringify($scope.CONFIG.karton));
}
}]);
The value of $scope.CONFIG is an object, localStorage only supports strings. Use JSON.stringify() and JSON.parse().
.controller("ExampleController", ['$scope', '$window', function($scope, $window) {
$scope.CONFIG = JSON.parse(localStorage.getItem('CONFIG'));
if (!$scope.CONFIG) {
$scope.CONFIG = {karton: true};
}
$scope.save = function(checked) {
$scope.CONFIG.karton = checked;
localStorage.setItem('CONFIG', JSON.stringify($scope.CONFIG));
}
}]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.