user3774047
user3774047

Reputation:

Number only input in angular js

Number only input:

HTML

    <input type="text" ng-model="employee.age" valid-input  
           input-pattern="[^0-9]+" placeholder="Enter an age" />
    </label> 

var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope) {
});

app.directive('validInput', function() {
  return {
    require: '?ngModel',
    scope: {
      "inputPattern": '@'
    },
    link: function(scope, element, attrs, ngModelCtrl) {

      var regexp = null;

      if (scope.inputPattern !== undefined) {
        regexp = new RegExp(scope.inputPattern, "g");
      }

      if(!ngModelCtrl) {
        return;
      }

      ngModelCtrl.$parsers.push(function(val) {
        if (regexp) {
          var clean = val.replace(regexp, '');
          if (val !== clean) {
            ngModelCtrl.$setViewValue(clean);
            ngModelCtrl.$render();
          }
          return clean;
        }
        else {
          return val;
        }

      });

      element.bind('keypress', function(event) {
        if(event.keyCode === 32) {
          event.preventDefault();
        }
      });
    }
}});

Why the above angularjs code so complicated? To have a number only text input can be done with normal javascript using regular expressions.

I wonder why such a lengthy code for angularjs being so famous?

Can't it be simpler than this?

Upvotes: 0

Views: 134

Answers (1)

Shushanth Pallegar
Shushanth Pallegar

Reputation: 2862

Try the below approach, hope it works including the trim of white spaces,

  <input type="text" ng-model="employee.age" 

   ng-pattern="^\d+$/|/[^\s*]/" placeholder="Enter an age" />

Upvotes: 1

Related Questions