0

在我引入本地存储之前,我的代码一直运行良好。我要做的是:当设备准备好时检查值是否存在,如果存在则获取它们。在函数的主体中,我为该变量范围分配了一个值,这就是我得到这个错误的地方。

$ionicPlatform.ready(function() {
if (localStorageService.get("modelTrue") == null) {
  $scope.userModal.show();
  localStorageService.set("modelTrue", "true")
}
else {
  //Parameter to restore:
  if(localStorageService.get("first") != null){
    $scope.data.firstDisplay = JSON.parse(localStorageService.get("first"));
  }
}; 
$scope.scanBarcode = function() {
                 $scope.data.firstDisplay = {'src' : 'img/1.png'}; //this is where I get the error
                 localStorageService.set("first", JSON.stringify($scope.data.firstDisplay));   
              }

当我调用最后一个函数时,我收到错误:“TypeError:无法设置属性 'firstDisplay' of null”。

我不明白这种行为。我只是将一个变量设置为一个值。这可能意味着什么?

null 来自 console.log($scope.data); 在此处输入图像描述

4

1 回答 1

2

您需要声明 $scope.data ={};否则它总是空的,

$ionicPlatform.ready(function() {
            $scope.data ={};
            if (localStorageService.get("modelTrue") == null) {
                $scope.userModal.show();
                localStorageService.set("modelTrue", "true")
            } else {
                //Parameter to restore:
                if (localStorageService.get("first") != null) {
                    $scope.data.firstDisplay = JSON.parse(localStorageService.get("first"));
                }
            };
            $scope.scanBarcode = function() {
                $scope.data.firstDisplay = {
                    'src': 'img/1.png'
                }; //this is where I get the error
                localStorageService.set("first", JSON.stringify($scope.data.firstDisplay));
            }
于 2016-11-14T06:28:50.627 回答