2015-12-02 60 views
1

我用Angularjs和Ionic制作了一个Todo应用程序。 我想保存到localStorage的一些字段,但是当我点击保存时,我得到这个错误。TypeError:无法读取null属性'push'

我的代码是:

angular.module('myApp', ['ionic']) 
    .controller('myAppCtrl', function($scope){ 

     $scope.uuid = function(){ 
      return Math.floor((1 + Math.random()) * 0x10000) 
       .toString(16) 
       .substring(1); 
     }; 

     $scope.todo = {}; 
     $scope.todos = {}; 

     //Check The Localstorage If the Todos exists 
     var todos = localStorage.getItem('todos'); 

     if(todos !== undefined){ 
      $scope.todos = JSON.parse(todos); 
     } 

     $scope.addTodo = function($event){ 
      activate_page("#create_edit"); 
     }; 

     $scope.goBack = function($event){ 
      activate_page("#mainpage"); 
     }; 

     $scope.saveTodo = function($event){ 

      $scope.todo.id = $scope.uuid(); 
      $scope.todos.push($scope.todo); 
      $scope.todo = {}; 
      localStorage.setItem('todos', JSON.stringify($scope.todos)); //Save 
      activate_page("#mainpage");    
     }; 
    }); 

你能帮助我吗? 谢谢

回答

2

您需要声明并初始化变量$ scope.todos像下面既然你推到一个对象没有阵列

$scope.todos = []; 
+0

:任何= [] ; – 2017-01-27 08:54:15

0

您试图push到一个JSON对象,不是数组,其像这样定义:

$scope.todos = [];

在角2 u可以使用待办事项
+1

与我的回答有什么不同? – Sajeetharan

+1

在同一时间发布,你只是更快一点。 – Spikee

相关问题