0

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?

1 Answer 1

1

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" /> 
Sign up to request clarification or add additional context in comments.

Comments