递减计数器无法正常工作

时间:2018-08-01 10:49:40

标签: javascript arrays angularjs counter

我正在尝试以4个数字/年的集执行增量和减量功能,其中导航应限制在4年的数组限制内。

每次点击增加按钮时,我都可以增加计数,但不能以相同的相反顺序递减。点击增加按钮后,递减按钮将被禁用,只有当我到达最后一个索引时,该按钮才会发生递增/递减,反之亦然

操场是here

 $scope.navigateYear=function(year, mode) {
       const index = $scope.yearArray.indexOf(year);
         if (index >= 0 && index < $scope.yearArray.length - 1 && mode === 'plus') {
             this.year = $scope.yearArray[index + 1];
        }else{
          $scope.isPlusButtondisabled=true;
        }
        if (index >= 0 && index < $scope.yearArray.length - 1 && mode === 'minus') {
            this.year = $scope.yearArray[index - 1];
        } else{
            $scope.isMinusButtondisabled=true;
        }
    }

我通过传递 plus minus

的模式来在同一功能中执行增量和减量运算

1 个答案:

答案 0 :(得分:2)

这里有一些问题:

  1. 如果单击加号按钮,则会禁用减号按钮,反之亦然,因为您在每个mode语句中检查了if
  2. 减号按钮if语句需要检查index> 0而不是>= 0
  3. 每当您递减/递增时,都应确保重新启用另一个按钮,以便可以向上/向下追溯几年。

我建议首先检查modeplus还是minus,然后从那里开始。

当他们plus的年份时,请检查index并根据需要增加/禁用plus按钮(并重新启用minus按钮)。反之亦然,minus模式。

    $scope.navigateYear=function(year, mode) {
       const index = $scope.yearArray.indexOf(year);

       if (mode === 'plus') {
         if (index >= 0 && index < $scope.yearArray.length - 1) {
               this.year = $scope.yearArray[index + 1];
               $scope.isMinusButtondisabled = false;
          }else{
            $scope.isPlusButtondisabled=true;
          }
       } else if (mode === 'minus') {
         if (index > 0 && index < $scope.yearArray.length) {
              this.year = $scope.yearArray[index - 1];
              $scope.isPlusButtondisabled = false;
          } else{
              $scope.isMinusButtondisabled=true;
          }
       }
    }

我希望这会有所帮助。

相关问题