使用 AngularJS 在输入字段上将输入限制为数字 [英] Restrict input as numbers on input fields using AngularJS

查看:32
本文介绍了使用 AngularJS 在输入字段上将输入限制为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将输入限制为以下字段中的数字

I am trying to restrict input as numbers on below 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)" />

它不适用于

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

它适用于以下代码,但更改了两个字段

It works with below code but changing both the fields

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

需要更改用户正在输入的输入字段的值,而不是两者

Need to change the value for the input field where user is typing and not both

推荐答案

使用此处找到的指令:https://stackoverflow.com/a/19675023/149060 而不是 ng-change 函数.复制到这里以供参考:

Use the directive found here: https://stackoverflow.com/a/19675023/149060 instead of the ng-change function. Replicated here for easy reference:

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;
            });
        }
    };
});

这篇关于使用 AngularJS 在输入字段上将输入限制为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆