Question

I have a voting widget where visitors to a site can vote up or down on their favorite game. However, visitors are able to down vote to the negatives too!

For example, if the current voteCount on my game object on the scope is set to 0, a user can come along, press the down arrow and change it to -1. How can I stop this from happening?

I can do this manually by doing a check before the voting happens, but is there no angular filter to do this?

Also, what is the quickest way to allow a user a single vote instead of endless votes? Would cookies be the quickest way? or HTML5's LocalStorage?

CTRL CODE

    myApp.controller('VotingCtrl', function($scope){
    $scope.games = [
        {
            name: 'Watch Dogs',
            description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut felis dapibus, bibendum dui eu.',
            imgUrl: 'img/watchdogs.jpg',
            voteCount: 0
        },
        {
            name: 'Thief',
            description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut felis dapibus, bibendum dui eu.',
            imgUrl: 'img/thief.jpg',
            voteCount: 0            
        },
        {
            name: 'Fifa 2014',
            description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ut felis dapibus, bibendum dui eu.',
            imgUrl: 'img/fifa2014.jpg',
            voteCount: 0
        }
    ]

    $scope.voteUp = function(game) {
        game.voteCount += 1;
    };

    $scope.voteDown = function(game) {
        game.voteCount -= 1;
    };
});
Was it helpful?

Solution

One way is to change your voteDown method to not decrement if voteCount = 0.

The other way (which I would prefer) is to disable downVote button if the voteCount has reached 0, using ng-disabled. This will make it clear to the user that he/she cannot downvote anymore.

Edit: Pseudo Code for using ng-disabled. In your view, you can do something like, assuming you are disabling a span.

<span ng-disabled="isDownVoteDisabled(game)"></span>

In your controller, you can define

$scope.isDownVoteDisabled = function(game) {
     return game.voteCount <= 0;
}

Abhi.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top