我有一个评论系统,每当单击upvote图标时,都需要将upvotes存储在数据库中。我具有的功能会增加数量,但刷新后会再次显示0。如何将其直接存储到数据库?这是代码:
在public / javascripts目录中的ang.js中:
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;
}
}]);
您需要c.update(comment)
在服务中创建一个方法,该方法接受注释以进行更新,然后$http.put()
在单击upvote按钮时在API中调用相应的方法来更新注释。
更新:另一个潜在的问题-如果您不是专门创建一个comment.upvotes
属性并将其默认设置为0,那么您comment.upvotes += 1
可能是在添加一个,null
或者undefined
不是真正添加一个。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句