nightowl
nightowl

Reputation: 120

How to slice/trim a $scope variable in AngularJS

I am new to AngularJS and I am trying to trim/slice/remove the last character from a variable ($scope.checkTotal) when ng-click="del()" is clicked.

Maybe my approach is wrong, but so far I've tried:

$scope.checkTotal.slice($scope.checkTotal, -1);

$scope.checkTotal.substring(0, $scope.checkTotal.length - 1);

$scope.checkTotal.substring(0, length - 1);


.controller('tipController', function($scope) {

  // Numpad
  $scope.checkTotal = '0.00';

  $scope.clicked = function (label) {
    if($scope.checkTotal === '0.00') {
      $scope.checkTotal = label;
    } else {
      $scope.checkTotal += label;
    }
   };

   // Prevent multiple decimals
   $scope.clickedDot = function() {
      if (($scope.checkTotal.indexOf('.') < 0) || ($scope.checkTotal === '0.00')) {
        if ($scope.checkTotal === '0.00') {
          $scope.checkTotal = '0.';
        } else {
          $scope.checkTotal += '.';
        }
      }
  };

   $scope.del = function () {
      $scope.checkTotal.substring(0, length - 1);
   };

});

Upvotes: 0

Views: 2956

Answers (3)

Rico Rojas
Rico Rojas

Reputation: 76

You need to reassign the result back to the variable. Slice also slices from start to end. Try this.

$scope.checkTotal = $scope.checkTotal.slice(0, -1);

Upvotes: 1

jeremy-denis
jeremy-denis

Reputation: 6878

Your approach is correct but the method slice wait the length of your variable (string or array). maybe you can try :

$scope.checkTotal = $scope.checkTotal.slice(0, $scope.checkTotal.length-1);

Upvotes: 1

The Head Rush
The Head Rush

Reputation: 3357

You need to assign the return values from the function calls. For example

$scope.checkTotal.substring(0, length - 1);

should be

$scope.checkTotal = $scope.checkTotal.substring(0, $scope.checkTotal.length - 1);

Also you should probably consider the case that someone clicks delete with nothing in the textbox. Would be awkward to get a $scope.checkTotal.substring(0, -1);

Upvotes: 3

Related Questions