Eedoh Eedoh - 6 months ago 104
AngularJS Question

How can I make input field accept INTEGERS only with AngularJS

How can I prevent typing anything except digits (integers) into an input field with angularJS

type="number" allows floating point numbers

I also tried several regexes with ng-pattern, but those floating points were still allowed, although I explicitly specified digits only.

I'm fiddling with watchers at the moment, but can't make them work properly, at least not yet. I'm thinking of writing keydown event handlers for these fields, but still hoping there's better way.

Answer

Create a directive may be?

myApp.directive("myNumber", function() {
  return {
    restrict: "EA",
    template: "<input type='number' step='1' />",
    replace: true,
    link: function(scope, e, attrs) {    
      e.bind("keydown", function(e) {

        if (!(e.keyCode >= 48 && e.keyCode <= 57)) {
          e.preventDefault();
        }
      });
    }
  };
});

then use it in your app like so

<div ng-app="myApp">
 <my-number><my-number>
</div>

You can garnish it further to allow bindings, and special keys

myApp.directive("myNumber", function() {
  return {
    restrict: "EA",
    template: "<input type='text' ng-model='model' />",
    replace: true,
    scope: {model : "="},
    link: function(scope, element, attrs) {
      var e = angular.element(element);

      e.bind("keydown", function(e) {
        if (!(e.ctrlKey || e.keyCode >= 48 && e.keyCode <= 57)) {
          e.preventDefault();
        }
      }).bind("change", function() {
         var e = angular.element(this);
         if (isNaN(parseInt(e.val())) || e.val().indexOf(".") >= 0) {
            alert("incorrect number value entered");
            e.val("");
         }
      });
    }
  };
});

Here is a working plunkr example

Here is more info on directives