简体   繁体   中英

how to remove the last character of an input field using AngularJS

The title of this question is probably wrong, but i can't think of how to name it. I'm trying to build a simple calculator using AngularJS. Right now its functioning, but i'm trying to add some other buttons. I want a "delete" key and a decimal key. The delete key is what i'm focused on now. If someone clicks, 3, then 3 again. we have 33. (this calculator currently, can only accept a left and right operand, and an operator separating them (ex, 3+3, or 56*486, etc). not multiple operators or operands). Now say the user were to enter 334, but they want the 4 taken off because they meant to click 5. How do I use javascript to delete the most recent number if an operator or equals hasn't been pressed? If i had to guess, it's going to be something like this:

$scope.deleteNumb = function(d){
        if(!$scope.operator){
            // if no operator, delete most recent left operand
        }
        else{ //delete most recent right operand}

        }
    };

The "C" button doesn't work. I had that set up as "Clear" which refreshed the page to start a new calculation. I need a way to figure out how to delete the existing answer without using location.reload();

So the main thing here, is trying to delete the recent most operand, whether it be left or right, depending if an operator has been clicked or not.

My code is here: https://codepen.io/tevon/pen/Moewba

For clear (C) did you try to clear all values in setClear

 $scope.setClear = function (a) {
          $scope.leftOperand = "";
        $scope.operator = "";
        $scope.rightOperand = "";
        $scope.answer = "";
        };

to delete a part of your number; have a look to substr as your input is a string :

For exemple :

 $scope.removeBtn = function(){

         var tmp = $scope.leftOperand;

         console.warn("test",tmp)
         $scope.leftOperand = tmp.substr(0,tmp.length-1);

       }

This function removes the last number of your leftOperand. Adapt it to your need for left/right

    $scope.setClear = function (a) {
       // $scope.clear = location.reload();
      var result = $scope.leftOperand + $scope.operator + $scope.rightOperand;
      result = result.substring(0, result.length - 1);

       if ($scope.operator){
            $scope.rightOperand = result;
        }
        else {
            $scope.leftOperand = result;
        }



    };

Not tested.. Would have to tweak a little when operators come i guess

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