【问题标题】:Angular.JS Uncaught TypeError: Cannot assign to read only propertyAngular.JS Uncaught TypeError:无法分配给只读属性
【发布时间】:2015-11-08 18:26:17
【问题描述】:

尽管尝试创建一个应用程序,并使用应保存到本地存储的切换设置,但结果并不好。

我正在使用 Ionic + Angular.JS

这是我的代码,我收到错误 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);
        }

}]);

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

【问题讨论】:

    标签: javascript android angularjs ionic-framework ionic


    【解决方案1】:

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

    【讨论】:

    • 使用这段代码,我得到一个空白屏幕,并显示错误“SyntaxError: Unexpected token o”,这是什么原因造成的,我该如何解决?
    猜你喜欢
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多