平均堆栈:如何将函数的结果更新到数据库
MEAN Stack: How to update a function's result to the database?
我有一个评论系统,每当单击赞成图标时,我都需要将赞成票存储在数据库中。我拥有的函数增加了数字,但一旦我刷新它,它就会再次显示 0。如何将其直接存储到数据库中?这是代码:
在 ang.js 在 public/javascripts 目录中:
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)
方法,该方法接受要更新的注释,然后在单击 upvote 按钮时调用 API 中的相应 $http.put()
方法来更新注释。
更新:另一个潜在问题 - 如果您没有专门创建 comment.upvotes
属性并将其默认设置为 0,那么您comment.upvotes += 1
可能会将一个添加到null
或undefined
,而不是真正添加一个。
相关文章:
- 为什么我的文本框没有用查询结果更新
- Angular JS根据搜索结果和点击事件更新DOM元素
- GoogleMapsForRails-只有在搜索结果发生变化时才通过ajax更新标记
- Angular$scope在更新时未将结果传递给父控制器
- ReactJS-这个状态中的数组在删除时被正确更新,但结果是't,直到以后的状态发生变化
- 使用动态变量名更新JSON中的结果
- Javascript错误,根据其他复选框的结果更新复选框/按钮
- 使用SimpleHTTPServer响应的结果更新javascript变量的值
- 平均堆栈:如何将函数的结果更新到数据库
- 如何在 mongodb 中获取更新查询写入结果
- 结果是检查多个复选框值并更新表数据
- 尝试从 jQuery 帖子结果更新选择列表选项
- Javascript:在输入更新后更新结果值
- 使用 AJAX 回调更新挖空可观察数组会生成随机排序的结果
- 从 JSON 结果更新 HTML 内容
- 表单与jquery结合PHP发送结果*更新完整的代码*
- 使用Python脚本的结果更新Javascript
- 从AJAX请求结果更新引导警报文本
- 尝试在jQuery中使用数学结果更新跨度
- 从ajax调用结果更新qtip内容