0

The idea is that the user should not be able to enter a decimal point while he tries to type in a number into the number-input-box. I thought of capturing the $event on the controller and then change the data on the input control. But this didn't work for me. I have this input box in the angular app web page:

<input type="number" ng-keydown="checkfordecimal($event, age)" min="1" max="125" name="inputage" ng-required="true" ng-model="model.age" />

controller:

$scope.checkfordecimal = function($event, age)
{
   if($event.which === 110 || $event.which === 190)
   {
    //do something
   }
 }

Can you think of a better way to achieve this?

AmitGupta
  • 43
  • 1
  • 6

2 Answers2

0

You could just kill all non decimal characters with RegEx like this:

$scope.checkfordecimal = function(){
   $scope.model.age = $scope.model.age.replace(/\D/g, '');//Remove all non decimal characters and store it in the model
}
  • The \D means "find every not digit"
  • The g flag means "global" or "check every character"

Then every match (like a dot) will be replaced with an empty string ('')

Nano
  • 1,398
  • 6
  • 20
  • 32
0

This should be a directive.
Here's one example that I've seen here (Credit to @My Mai):

  app.directive('onlyDigits', function () {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function (scope, element, attr, ctrl) {
        function inputValue(val) {
          if (val) {
            var digits = val.replace(/[^0-9]/g, '');

            if (digits !== val) {
              ctrl.$setViewValue(digits);
              ctrl.$render();
            }
            return parseInt(digits,10);
          }
          return undefined;
        }            
        ctrl.$parsers.push(inputValue);
      }
    };
});

Usage:

<input type="text" name="number" only-digits>
Community
  • 1
  • 1
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
  • This works! With few tweaks, I was able to customize my requirement. Thank you Amir Popvich. – AmitGupta Apr 28 '15 at 07:04
  • who calls the method "inputValue()". Is it called automatically when the user enters a value into the inputbox? If yes, then the method wont be called when the user enters a period (".") in the first place incase of a text box. (as "." will not be considered as a value. – AmitGupta Jun 15 '15 at 10:26
  • @user2902287 Functions added to $parsers are called as soon as the value in the form input is modified by the user. Google it and read more about it. – Amir Popovich Jun 15 '15 at 11:25