如何精确地加1或减去1的值

时间:2014-12-03 01:42:29

标签: javascript arrays json angularjs

我在数组中有一些值。假设我在facebook中使用的是喜欢和不喜欢的选项。用户只能给1个喜欢或1个不喜欢。如果不喜欢,就像变成0而如果喜欢,则不喜欢变成0。

  1. 喜欢和不喜欢数字不应该给出负值。 -ve值应舍入为0。
  2. for like = 24& dislike = 0:用户只能选择喜欢或不喜欢一次。即,当选择喜欢的时候 - 就像是25&如果选择不喜欢,就像变成24而不喜欢仍然为0,但不喜欢与0保持相同。但是值24不应该达到26。
  3. for like = 0 and dislike = 15:当用户选择喜欢时,如果选择不喜欢就变成1而不喜欢变成14.不喜欢变成15,喜欢变成0。
  4. for like = 32&不喜欢= 12:如果用户选择喜欢,就像变成33而不喜欢变成11.如果用户选择不喜欢,则不喜欢变成12然后再变为32.如果用户选择喜欢,则变为11,反之亦然。这该怎么做?请帮忙。
  5. //代码

    <li ng-repeat="employee in data.employees">
                <button ng-click="like();">Like</button>
    
                 {{employee.x}}
    
                <button ng-click="dislike()">Dislike</button>
    
                 {{employee.y}}
              </li>
    

    samplelink

2 个答案:

答案 0 :(得分:1)

您可以在添加和减去喜欢的liked处理程序中为每个disliked添加employeeng-click属性。

$scope.like = function(employee){
  employee.x = parseInt(employee.x) + 1;
  if (parseInt(employee.y) > 0)      
    employee.y = parseInt(employee.y) - 1;
  employee.liked = true;
  employee.disliked = false;
}

$scope.dislike = function(employee){
  if (parseInt(employee.x) > 0)      
    employee.x = parseInt(employee.x) - 1;
  employee.y = parseInt(employee.y) + 1;
  employee.liked = false;
  employee.disliked = true;
}

然后,ng-disabled可以阻止额外点击。

<li ng-repeat="employee in data.employees">
  <button ng-click="like(employee)" ng-disabled="employee.liked">Inc</button>
  like: {{employee.x}}

  <button ng-click="dislike(employee)" ng-disabled="employee.disliked">Dec</button>
  dislike: {{employee.y}}
</li>

http://plnkr.co/edit/qRdp4io5pdfxL7KijTjy?p=preview

答案 1 :(得分:0)

它现在有效..!

  <li ng-repeat="employee in data.employees">
    <button ng-disabled="employee.edited" ng-click="like($index);">Inc</button>
    like: {{employee.x}}

    <button ng-disabled="employee.edited" ng-click="dislike($index)">Dec</button>
     dislike: {{employee.y}}
  </li>

我将编辑后的属性添加到员工禁用按钮

 $scope.data = {"employees":[
    {"x":"0", "y":"0", 'edited':false}, 
    {"x":"24", "y":"0", 'edited':false}, 
    {"x":"0", "y":"15", 'edited':false}, 
    {"x":"32", "y":"12", 'edited':false}, 
]};


function like(index){
  $scope.data.employees[index].edited = true;
  $scope.data.employees[index].x = parseInt($scope.data.employees[index].x) + 1;   
  if(parseInt($scope.data.employees[index].y) !== 0)
    $scope.data.employees[index].y = parseInt($scope.data.employees[index].y) - 1;

}

function dislike(index){
  $scope.data.employees[index].edited = true;
  if(parseInt($scope.data.employees[index].x) !== 0)
    $scope.data.employees[index].x = parseInt($scope.data.employees[index].x) - 1; 
  $scope.data.employees[index].y = parseInt($scope.data.employees[index].y) + 1;  
}

用于已修改的代码plunker