Angular.JS Uncaught TypeError:无法分配给只读属性

时间:2015-11-08 18:26:18

标签: javascript android angularjs ionic-framework ionic

尝试使用应该保存到本地存储的切换设置来创建应用程序,但它没有太多运气。

我正在使用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>

修改

我现在有了这个,但它在控制台日志中返回“undefined”:

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

1 个答案:

答案 0 :(得分:2)

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