角度指令忽略非数字输入 [英] angular directive ignore non-numeric input

查看:26
本文介绍了角度指令忽略非数字输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to write some code for IE8. I have an ng-repeat creating a table filled with:

<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

IE8 won't do type=number

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

I want a directive that will ignore key strokes on that input field that are NOT numeric keys....ie....0 - 9

我不想让用户键入 abc 并污染模型,然后告诉他们该值无效.我宁愿不让他们输入任何一开始就无效的数据.

I don't want to let the user type abc and pollute the model and then tell them the value is invalid. I'd rather not let them enter any data that's not valid in the first place.

推荐答案

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

另见输入中ng-model的过滤器.我上面的回答是模仿 pkozlowski.opensource 的回答.

See also filters on ng-model in an input. My answer above is modeled off pkozlowski.opensource's answer.

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

I looked at ng-pattern, but it does not filter what is shown in the textbox. It sets $scope.qty1 to undefined, but the undesired characters are visible in the textbox.

这篇关于角度指令忽略非数字输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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