On my HTML page, I have an input box that is bound to an ng-model and restricted to only accept numbers using a custom directive. I am unable to utilize the default HTML5 restrictions like type="number". The issue I'm facing is that if a non-digit character is entered twice (e.g., typing 123 followed by 'k' twice), the 'k' gets appended to the number resulting in '123k'. However, upon typing another key, the 'k' is automatically removed by the directive.
I need assistance in resolving the problem of non-numeric characters appearing when the same key is pressed multiple times.
Below is the code for the directive I am using:
angular.module('app').
directive('onlyDigits', function () {
return {
restrict: 'A',
require: '?ngModel',
link: function (scope, element, attrs, ngModel) {
if (!ngModel) return;
ngModel.$parsers.unshift(function (inputValue) {
var digits = inputValue.split('').filter(function (s) { return (!isNaN(s) && s !== ' '); }).join('');
ngModel.$viewValue = digits;
ngModel.$render();
return digits;
});
}
};
});