简体   繁体   中英

Vote once per post in Angular app

Right now a user can only vote up or down once in general. I want a user to be able to vote up or down once per post.

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

Controller:

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

Service:

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

Instead of checking global upvoted variable, check it against each post.

Your controller should be something like this,

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

The idea is to have upvoted variable locally for each post.

Hope it helps. If any doubt ask in comments.

upvoted is scoped to the entire controllers, so when you check if(!upvoted) , if the user has voted once, that block will not run. Check instead if(!post.hadUpvoted) as that is scoped to each post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM