我试图在下面的字段中限制输入为数字
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)" />
它不适用于
$scope.myNumbers = function(fieldName){ var tN = fieldName.replace(/[^\d]/g, ""); if(tN != fieldName) fieldName = tN };
它适用于以下代码,但同时更改了两个字段
$scope.$watch('myNumbers', function() { var tN = $scope.myNumbers.replace(/[^\d]/g, ""); if(tN != $scope.myNumbers) $scope.myNumbers = tN; })
需要更改用户正在输入的输入字段的值,而不是两者都更改
使用此处找到的指令:而不是ng-change函数。复制此处以方便参考:
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; }); } }; });