Here is the directive I made to restrict the allowed keys.
angular.module('app').directive('restrictTo', function() { return { restrict: 'A', link: function (scope, element, attrs) { var re = RegExp(attrs.restrictTo); var exclude = /Backspace|Enter|Tab|Delete|Del|ArrowUp|Up|ArrowDown|Down|ArrowLeft|Left|ArrowRight|Right/; element[0].addEventListener('keydown', function(event) { if (!exclude.test(event.key) && !re.test(event.key)) { event.preventDefault(); } }); } } });
And the input will look like this:
<input type="text" name="zipCode1" maxlength="5" ng-model="zipCode1" restrict-to="[0-9]">
A regular expression evaluates the key pressed, not the value .
It also works great with type="number" inputs, because it does not allow changing its value, so the key is never displayed, and it does not bother with the model.
ragnar Nov 17 '16 at 13:34 2016-11-17 13:34
source share