AngularJS 1.x directive to allow only numbers in text field.
angular.module('myModule').directive('numbersOnly', function () {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModelCtrl) {
function fromUser(text) {
if (text) {
var transformedInput = text.replace(/[^0-9]/g, '');
if (attr.max) {
transformedInput = text.substr(0, attr.max);
}
transformedInput = transformedInput.replace(/[^0-9]/g, '');
if (transformedInput !== text) {
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
}
return transformedInput;
}
return '';
}
ngModelCtrl.$parsers.push(fromUser);
}
};
})