如何建立起来angularjs /向下投票功能 [英] how to create up/down voting function in angularjs

查看:159
本文介绍了如何建立起来angularjs /向下投票功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨可能我知道我可以创建一个angularjs向上/向下投票功能?我想把它做类似的东西计算器或reddit的。
我发现,做什么jQuery插件 https://github.com/janosgyerik/jquery-upvote 我想,但其在jQuery中。

Hey guys may i know how can i create a up/down voting function in angularjs ? i want to make it to something similar to stackoverflow or reddit. i found a Jquery plugin https://github.com/janosgyerik/jquery-upvote that does what i want but its in Jquery.

我尝试了好几种方法来做到这一点,但我仍然不能得到它工作得很好。这里是我的方法。

i have tried several approach to do it but i still can't get it works well. here's my approach.

HTML

<a class="green" ng-click="isUpVoted = !isUpVoted"  ng-style="afterVoteUp" href=""> <i title="Up Votes" class="fa fa-arrow-circle-up fa-2x"></i></a>

<a class="maroon" ng-click="isDownVoted = !isDownVoted" ng-style="afterVoteDown" href="" > <i title="Down Votes" class="fa fa-arrow-circle-down fa-2x "></i></a>

控制器

$scope.isUpVoted = false;
    $scope.$watch("isUpVoted",function(newVal, oldVal){
    if(newVal != oldVal){
        if(newVal){
           // first click
           // upvote

        }else{
           // second click 
           // remove upvote
        }

        }
});

$scope.isDownVoted = false;
        $scope.$watch("isDownVoted",function(newVal, oldVal){
        if(newVal != oldVal){
            if(newVal){
               // first click
               // downvote

            }else{
               // second click 
               // remove downvote
            }

            }
    });

这工作了一键完全正常,但是我仍然无法弄清楚如何使这2个按键一起工作,例如,当用户点击给予好评downvote将取消,反之亦然,然后再次单击给予好评取消投票。

which work completely fine for one button, however i still can't figure out how to make this 2 buttons work together, for example when user click upvote downvote will cancel or vice versa and click the upvote again to cancel vote.

推荐答案

只需使用一个单一的范围变量像一个切换按钮。

Just use a single scope variable to act like a toggle button.

样品展示: http://plnkr.co /编辑/ C4w9hDK3xW1R0ua3WPgU?p = preVIEW

HTML:

<body ng-controller="MainCtrl">
  <i title="Up Votes" ng-click="changeVote(vote, 'up')" class="fa fa-arrow-circle-up fa-2x" ng-class="{true:'up', false:''}[vote=='up']"></i>
  <br>
  <i title="Down Votes" ng-click="changeVote(vote, 'down')" class="fa fa-arrow-circle-down fa-2x"  ng-class="{true:'down', false:''}[vote=='down']"></i>
  <br>Vote: {{vote}}

控制器逻辑:

app.controller('MainCtrl', function($scope) {
  $scope.changeVote = function(vote, flag) {
    $scope.vote = vote == flag ? 'None' : flag;
    alert($scope.vote);
  };
});

这篇关于如何建立起来angularjs /向下投票功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆