Angular.JS未捕获类型错误:无法分配给只读属性

Angular.JS Uncaught TypeError: Cannot assign to read only property

本文关键字:分配 只读属性 错误 JS 类型 Angular      更新时间:2023-09-26

尽管试图创建一个应用程序,但它的切换设置应该保存到本地存储,但运气并不好。

我正在使用Ionic+Angular.JS

这是我的代码,我得到了错误Uncaught TypeError:无法分配给只读属性

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);
        }
}]);

HTML文件:

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

编辑

我现在有了这个,但它在控制台日志中返回了一个"未定义":

.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));
        }
}]);

$scope.CONFIG的值是一个对象,localStorage只支持字符串。使用JSON.stringify()和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));
        }
}]);