繁体   English   中英

TypeError:无法读取null的属性“ push”

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM