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

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

问题描述

我必须写一些code为IE8。我有一个NG重复创建充满表:

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不会做类型=号

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

又见<一个href=\"http://stackoverflow.com/questions/14419651/angularjs-filters-on-ng-model-in-an-input\">angularjs过滤器上输入 NG-模式。我的回答上面是仿照了pkozlowski.opensource的答案。

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

我看着NG-模式,但它并不过滤是什么在文本框中显示。它集 $ scope.qty1 未定义,但不想要的字符在文本框中可见。

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天全站免登陆