Limit input as numbers to input fields using AngularJS

I am trying to limit the input as numbers in the underlying fields

Postal Code: <input type="text" id="zipCode1" name="zipCode1" size="4" maxlength="5" ng-model="zipCode1" ng-change="myNumbers(zipCode1)" /> <input type="text" id="zipCode2" name="zipCode2" size="3" maxlength="4" ng-model="zipCode2" ng-change="myNumbers(zipCode2)" /> 

he does not work with

 $scope.myNumbers = function(fieldName){ var tN = fieldName.replace(/[^\d]/g, ""); if(tN != fieldName) fieldName = tN }; 

It works with the code below, but changing both fields

 $scope.$watch('myNumbers', function() { var tN = $scope.myNumbers.replace(/[^\d]/g, ""); if(tN != $scope.myNumbers) $scope.myNumbers = tN; }) 

You must change the value for the input field where the user enters text, not both

+3
angularjs
Jan 29 '14 at 13:34
source share
3 answers

Use the directive found here: https://stackoverflow.com> Replicated here for convenience:

 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; }); } }; }); 
+4
Jan 29 '14 at 13:49
source share

You can try adding to the inputs.

  ng-pattern = '/ ^ \ d {2} $ /' 
+2
Jan 29 '14 at 1:37
source share

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.

+2
Nov 17 '16 at 13:34
source share



All Articles