问题
I'm having a commenting system and I need to store the upvotes in the database whenever the upvote icon is clicked. The function I have increases the number but as soon as I refresh it, it says 0 again. How do I store it directly to the database? Here is the code:
In the ang.js in the public/javascripts directory:
var app=angular.module('peopleComments',['ui.router']);
app.factory('comments',['$http', function($http){
var c={
comments:[]
};
//loading all existing comments with getAll()
c.getAll=function(){
return $http.get('/comments').success(function(data){
angular.copy(data, c.comments);
});
};
//function which creates the new comments for updating in the database
c.create = function(comment) {
return $http.post('/comments', comment).success(function(data){
c.comments.push(data);
});};
return c;
}]);
app.controller('Base',[
'$scope','comments',function($scope,comments){
$scope.comments=comments.comments;
$scope.addComment=function(){
if(!$scope.username||$scope.username==''){$scope.username='Anonymous';}
if(!$scope.contents||$scope.contents==''){return;}
comments.create({
username: $scope.username,
contents: $scope.contents,
});
$scope.username='';
$scope.contents='';
}
$scope.increaseUpvotes=function(comment){ //function which updates the upvotes
comment.upvotes+=1;
}
}]);
回答1:
You need to create a c.update(comment)
method in your service that takes a comment to update and then calls a corresponding $http.put()
method in your API to update the comment when the upvote button is clicked.
Update: One more potential issue - if you are not specifically creating a comment.upvotes
property and setting it to 0 by default then your comment.upvotes += 1
might be adding one to null
or undefined
and not really adding one.
来源:https://stackoverflow.com/questions/36117403/mean-stack-how-to-update-a-functions-result-to-the-database