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

Vote once per post in Angular app

本文关键字:一次 应用程序 Angular      更新时间:2023-09-26

现在,用户通常只能投一次赞成票或反对票。我希望用户能够在每个帖子中投票一次。

<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>

控制器:

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

服务:

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; 
        });
};

与其检查全局upvoted变量,不如针对每个post进行检查。

你的控制器应该是这样的,

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

其想法是为每个帖子本地设置upvoted变量。

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

upvoted的作用域为整个控制器,因此当您检查if(!upvoted)时,如果用户投票一次,则该块将不会运行。请改为选中if(!post.hadUpvoted),因为它的作用域是每个帖子。