简体   繁体   中英

Decrement counter not working as expected with respect to increment counter-angular js

I'm trying to perform increment and decrement function with set of 4 numbers/years as in which the navigation should be restricted within the array limit of 4 years.

I'm able to increment the count on each click of Increment button but not able to decrement in the same reverse order.Also the button for decrement gets disabled once I click on increment which should happen only I reach the last index of increment/decrement and vice versa

Playground is 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;
        }
    }

I'm performing both increment and decrement operations in the same function by passing mode as plus or minus

There are a few of issues here:

  1. You are disabling the minus button if the plus button is clicked and vice versa because you check the mode in each if statement.
  2. The minus button if statement needs to check if the index is > 0 instead of >= 0
  3. Whenever you decrement / increment, you should make sure that the other button is re-enabled so you can go back up / down years.

What I would recommend is to start by checking if the mode is plus or minus , then go from there.

When they plus the year, then check the index and increment / disable the plus button as needed (and re-enable the minus button). And vice versa for the minus mode.

    $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;
          }
       }
    }

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM