我正在使用此Angular项目,用户提交评论表单,新评论将添加到已发布的评论中。这是我的代码。
.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;
})
};
然而,当我尝试添加评论时,我收到以下错误。
TypeError: Cannot read property 'push' of undefined
我已经定义了一个空的$ scope.comments = {};那我为什么会收到这个错误呢?我该如何解决?感谢
答案 0 :(得分:10)
您声明的评论是一个对象。只需将声明更改为数组,
发件人:强>
$scope.comments = {};
要强>
$scope.comments = [];
修改强> 如果你需要推送新对象,你需要像这样将你的注释作为对象数组并推送新的对象
$scope.comments = {
1: {name:'',review:'',comment:'',uptime:'',gravatar:''}
}
$scope.comments.push({name:'rukshi', review:'test comment',comment:'yet another comment',uptime:'',gravatar:''});
答案 1 :(得分:2)
你可以试试这个
.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;
})
};