Javascript 在Angular应用程序中为每个帖子投票一次

Javascript 在Angular应用程序中为每个帖子投票一次,javascript,angularjs,Javascript,Angularjs,目前,用户通常只能投一次赞成票或反对票。我希望一个用户能够投票向上或向下每个职位一次 <div ng-repeat="post in posts | orderBy:'-upvotes'"> <span class="glyphicon glyphicon-thumbs-up" ng-click="incrementUpvotes(post)" ng-style="post.hadUpvoted ? {color: 'red'} : {}"><

目前,用户通常只能投一次赞成票或反对票。我希望一个用户能够投票向上或向下每个职位一次

<div ng-repeat="post in posts | orderBy:'-upvotes'">

    <span class="glyphicon glyphicon-thumbs-up"
      ng-click="incrementUpvotes(post)" ng-style="post.hadUpvoted ? {color: 'red'} : {}"></span>
    {{post.upvotes}}

    <span class="glyphicon glyphicon-thumbs-down" ng-click="downvote(post)" 
      ng-style="post.hadDownvoted ? {color:'red'} : {}"></span>
服务:

o.upvoteComment = function(post, comment) {
    return $http.put('/posts/' + post._id + '/comments/' + comment._id + '/upvote', null, {
        headers: {Authorization: 'Bearer '+auth.getToken()}
        }).success(function(data) {
            comment.upvotes += 1; 
        });
};

不要检查全局
向上投票的
变量,而是针对每个帖子检查它

你的控制器应该是这样的

$scope.incrementUpvotes = function(post) {
    if(!post.hadUpvoted) {
        posts.upvote(post);
        post.hadUpvoted = true; 
    }
};
我们的想法是为每个帖子在本地设置
向上投票
变量


希望能有帮助。如果有任何疑问,请在评论中提问。

向上投票
适用于整个控制器,因此当您检查
如果(!向上投票)
,如果用户已投票一次,则该块将不会运行。如果(!post.haduppoitted)
,则改为选中

$scope.incrementUpvotes = function(post) {
    if(!post.hadUpvoted) {
        posts.upvote(post);
        post.hadUpvoted = true; 
    }
};