Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Cannot read property 'push' of undefined, JavaScript

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

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

like image 573
rksh Avatar asked Apr 09 '15 04:04

rksh


1 Answers

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

From:

$scope.comments = {};

To:

$scope.comments = [];

EDIT: 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:''});
like image 114
Sajeetharan Avatar answered Sep 28 '22 06:09

Sajeetharan