类型错误:无法读取未定义,JavaScript的财产'推' [英] TypeError: Cannot read property 'push' of undefined, JavaScript

查看:226
本文介绍了类型错误:无法读取未定义,JavaScript的财产'推'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用户提交评论形式是角项目的工作,新的评论将被添加到这已经发布的评论。这里是我的code。

I'm working in this Angular project where user submits a comment form, and the new comment is added to the comments that's already posted. Here is my code.

.controller('productCtrl', function($scope, $http, $routeParams, Page){
$scope.product = {};
$scope.review = {};
$scope.comments = {};

routeparm = $routeParams.param;

$scope.review = function(){
    var review_box = $scope.review_form.review_box;

    $http.post('./comment.php', {
        comment : review_box,
        code: routeparm
    })

    .success(function(data){
            $scope.comments.push(data.comments);
            $scope.review.review_box = '';
    })

    .error(function(data){
        $scope.has_error = true;
        $scope.error_message = data;
    })

};

然而,当我尝试添加评论,我得到了下面的错误。

However when I try to add a comment I get the following error.

TypeError: Cannot read property 'push' of undefined

我定义一个空$ scope.comments = {};所以为什么我收到此错误?我该如何解决?谢谢

I've defined an empty $scope.comments = {}; so why am I getting this error? And how can I fix it? Thanks

推荐答案

您已经声明的意见是一个对象。只是你的宣言变成一个数组,

The comments you have declared is an Object. Just change your declaration to an array ,

发件人:

$scope.comments = {};

$scope.comments = [];

编辑:
如果您需要推新对象,你需要让你的评论是这样的对象数组和推新对象

If you need to Push new Object, You need to make your Comments as Array of Object like this and push the new Object

$scope.comments = { 
    1: {name:'',review:'',comment:'',uptime:'',gravatar:''}
}

 $scope.comments.push({name:'rukshi', review:'test comment',comment:'yet another comment',uptime:'',gravatar:''});

这篇关于类型错误:无法读取未定义,JavaScript的财产'推'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆