我用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");
};
});
你能帮帮我吗?
谢谢
答案 0 :(得分:2)
您需要声明并初始化变量$ scope.todos,如下所示:因为您要推送对象而不是数组
$scope.todos = [];
答案 1 :(得分:0)
您正在尝试push
到JSON对象,而不是数组,其定义如下:
$scope.todos = [];