有没有办法在AngularJs中只投票一次?

时间:2015-11-24 17:22:48

标签: javascript angularjs

以下代码来自Code Academy的AngularJS课程。在第一课中,为用户提供了评级选项,例如'或者不喜欢'。一旦用户点击'喜欢'按钮投票上升,同样用户点击“不喜欢”'按钮将投票添加到减号。但是,代码中没有办法限制用户仅向上或向下投票一次。有没有办法使用AngularJS限制用户投票一次?

html代码



<div class="rating">
        <p class="likes" ng-click="plusOne($index)">+{{product.likes}}</p>
        <p class="dislikes" ng-click="minusOne($index)">-{{product.dislikes}}</p>
</div>
&#13;
&#13;
&#13;

AngularJS代码

&#13;
&#13;
app.controller('MainController', ['$scope',
  function($scope) {
    $scope.title = 'Top Sellers in Books in this Great City';
    $scope.promo = 'Our Christmas Promo is on the way!';
    $scope.products = [{
      name: 'The Book of Trees',
      price: 19,
      pubdate: new Date('2014', '03', '08'),
      cover: 'img/the-book-of-trees.jpg',
      likes: 0,
      dislikes: 0
    }, {
      name: 'Program or be Programmed',
      price: 8,
      pubdate: new Date('2013', '08', '01'),
      cover: 'img/program-or-be-programmed.jpg',
      likes: 0,
      dislikes: 0
    }, {
      name: 'Book1',
      price: 8,
      pubdate: new Date('2015', '04', '02'),
      cover: 'img/..',
      likes: 0,
      dislikes: 0
    }, {
      name: 'Book2',
      price: 8,
      pubdate: new Date('2015', '09', '09'),
      cover: 'img/..',
      likes: 0,
      dislikes: 0
    }];
    $scope.plusOne = function(index) {
      $scope.products[index].likes += 1;
    };
    $scope.minusOne = function(index) {
      $scope.products[index].dislikes += 1;
    };
  }
]);
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

是的,只需标记数组中的对象。

$scope.plusOne = function(index) {
    if(!$scope.products[index].upvoted){
      $scope.products[index].likes += 1;
      $scope.products[index].upvoted = true;
    }
};
$scope.minusOne = function(index) {
    if(!$scope.products[index].downvoted){
      $scope.products[index].dislikes += 1;
      $scope.products[index].downvoted = true;
    }
};

如果你想要一个upvote来否定一个downvote(反之亦然),你将不得不加一点点,但这是微不足道的。