【问题标题】:Only accepting numbers in an input field. The angular way (without html5)仅接受输入字段中的数字。角度方式(不带html5)
【发布时间】:2016-08-24 11:22:16
【问题描述】:

我有一个应该只接受数字的字段,我知道我们通常会接受 input type="number"。角度中只允许数字的最佳方法是什么?

【问题讨论】:

标签: angularjs input


【解决方案1】:

你可以创建一个类似下面给出的指令,然后在 HTML 元素中使用它作为一个属性

.directive('validNumber', function () {
        return {
            restrict: 'A',
            require: '?ngModel',
            link: function (scope, element, attrs, ngModelCtrl) {

                //8:"BACKSPACE",9:"TAB",17:"CTRL",18:"ALT",37:"LEFT",
                //38:"UP",39:"RIGHT",40:"DOWN",45:"INSERT",46:"DELETE",
                //48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9", 67:"C",86:"V",
                //96:"0",97:"1",98:"2",99:"3",100:"4",101:"5",102:"6",103:"7",104:"8",105:"9",
                //109:"-",110:".",144:"NUMLOCK", 189:"-",190:".",

                var keyCode = [8, 9, 17, 37, 38, 39, 40, 45, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 67, 86, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 109, 110, 144, 189, 190];
                element.bind("keydown", function (event) {
                    if ($.inArray(event.which, keyCode) == -1) {
                        scope.$apply(function () {
                            scope.$eval(attrs.validNumber);
                            event.preventDefault();
                        });
                        event.preventDefault();
                    }

                });
            }
        };
    });

【讨论】:

    【解决方案2】:

    也许你可以利用这个简单的指令..

     // ---Directive for Digit restriction on input fields.---------
    
    myApp.directive('numbersOnly', function() {
    return {
        require : 'ngModel',
        link : function(scope, element, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function(inputValue) {
                // if the input is 'undefined'
                if (inputValue == undefined)
                    return ''
                var transformedInput = inputValue.replace(/[^0-9]/g, '');
                if (transformedInput != inputValue) {
                    modelCtrl.$setViewValue(transformedInput);
                    modelCtrl.$render();
                }
    
                return transformedInput;
            });
        }
    };
    

    });

    在 HTML 中,您可以将指令声明为

    <input type="numbers" numbers-only  ng-model="numberModel">
    

    因此,理想情况下,此输入字段将使用数字作为唯一数据更新您的模型..

    这里发生的情况是,每次按下一个字符时,它都会受到我们的指令 numbersOnly 的监控,在这里您只选择数字作为输入。

    希望对您有所帮助... 干杯

    【讨论】:

      猜你喜欢
      • 2017-05-18
      • 2021-09-05
      • 2015-03-09
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多