![](/img/trans.png)
[英]TypeError: Cannot read property 'push' of null when inserting first value
[英]TypeError: Cannot read property 'push' of null
我使用Angularjs和Ionic制作了Todo應用程序。 我想將某些字段保存到localStorage,但是當我單擊“保存”時,出現此錯誤。
我的代碼是:
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");
};
});
你能幫助我嗎? 謝謝
您需要像下面那樣聲明和初始化變量$ scope.todos,因為您要推送到對象而不是數組
$scope.todos = [];
您嘗試push
送到JSON對象,而不是數組,其定義如下:
$scope.todos = [];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.