LifeLess LifeLess - 1 month ago 12
HTML Question

AngularJS - How to put number 0 if input isn't numeric

I wish there was TryParse but I guess there isn't in AngularJS. I tried to use

angular.isNumber()
. What I want my program to do: to replace any not numeric input with number
0
. What it actually does: input box ignores anything which is not numeric by not allowing to write it down.

<script>
var app = angular.module('BindingsApp', []);

app.controller('InputCtrl', function($scope) {
$scope.num3 = 0;
$scope.edit = function () {

$scope.num1 = parseInt($scope.num1);
$scope.num2 = parseInt($scope.num2);

function isNumeric(num) {
return !isNaN(num);
}

if (!angular.isNumber($scope.num1) ) {
$scope.num1 = 0;
}

if (!angular.isNumber($scope.num2) ) {
$scope.num2 = 0;
}

$scope.num3 = $scope.num1 + $scope.num2;
};
});
</script>





<input type="text" ng-model="num1" ng-change="edit()" value="isNumeric(num1)" />
<br />
<input type="text" ng-model="num2" ng-change="edit()" value="{{num2}}" />
<br />
<input type="text" ng-model="num3" ng-change="edit()" value="{{num3}}" />
<br />




Answer

Easy way is to replace

<input type="text" ng-model="num1" ng-change="edit()" value="isNumeric(num1)" />
<br />

To

<input type="number" ng-model="num1" ng-change="edit()" />
<br />

type="number" which will allow only numeric values.No need to write any extra code

EDIT: Inorder to replace non-numeric values to 0 and allow numeric values, here is a directive

app.directive('productionQty', function() {
  return {
    require: 'ngModel',
    link: function (scope, element, attr, ngModelCtrl) {
      function fromUser(text) {
        var transformedInput = text.replace(/[^0-9]/g, '0');
        console.log(transformedInput);
        if(transformedInput !== text) {
            ngModelCtrl.$setViewValue(transformedInput);
            ngModelCtrl.$render();
        }
        return transformedInput;
      }
      ngModelCtrl.$parsers.push(fromUser);
    }
  }; 
});

DEMO