angular指令忽略非数字输入

时间:2013-03-21 18:05:29

标签: javascript angularjs angularjs-directive

我必须为IE8编写一些代码。我有一个ng-repeat创建一个填充的表:

<input production-qty type="text" class="input-mini" maxlength="3" ng-model="day.qtyA" ui-event="{ blur : 'updateProduction(day)' }" ng-disabled="day.type=='H'">

IE8不会执行type = number

我想要一个忽略该输入字段上不是数字键的键击的指令....即...... 0 - 9

我不想让用户键入abc并污染模型,然后告诉他们值无效。我宁愿不让他们输入任何首先无效的数据。

4 个答案:

答案 0 :(得分:43)

HTML:

<input production-qty type="text" maxlength="3" ng-model="qty1">

指令:

app.directive('productionQty', function() {
  return {
    require: 'ngModel',
    link: function (scope, element, attr, ngModelCtrl) {
      function fromUser(text) {
        var transformedInput = text.replace(/[^0-9]/g, '');
        console.log(transformedInput);
        if(transformedInput !== text) {
            ngModelCtrl.$setViewValue(transformedInput);
            ngModelCtrl.$render();
        }
        return transformedInput;  // or return Number(transformedInput)
      }
      ngModelCtrl.$parsers.push(fromUser);
    }
  }; 
});

Plunker

另见filters on ng-model in an input。我上面的答案是以pkozlowski.opensource的答案为蓝本的。

我查看了ng-pattern,但它没有过滤文本框中显示的内容。它将$scope.qty1设置为undefined,但不需要的字符在文本框中可见。

答案 1 :(得分:8)

HTML:

<input type="number" name="graduationYear" ng-model="gradYear" only-num>

指令:

directive('onlyNum', function() {
    return function(scope, element, attrs) {

        var keyCode = [8, 9, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 110];
        element.bind("keydown", function(event) {
            //console.log($.inArray(event.which,keyCode));
            if ($.inArray(event.which, keyCode) === -1) {
                scope.$apply(function() {
                    scope.$eval(attrs.onlyNum);
                    event.preventDefault();
                });
                event.preventDefault();
            }

        });
    };
});

答案 2 :(得分:0)

首先在js文件中包含此代码 numericInput.js

指令: -

.directive('numeric', function() {
    return function(scope, element, attrs) {

        $(element[0]).numericInput({ allowFloat: true });

    };
})

HTML: -

 <input type="text" numeric />

DEMO Numeric Demo

答案 3 :(得分:-2)

不是指令,但我只使用:

控制器:

    $scope.blockNonNumber = function (val, field){

       $scope[field] = val.toString().replace(/[^0-9]/g, '');

    }

HTML:

<input type="text" ng-model="price" ng-change="blockNonNumber(price, 'price')" pattern="[0-99]">

它不是指令,但可以在指令中用作井旁

相关问题