Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

javascript - angular directive ignore non-numeric input

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 won't do type=number

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

HTML:

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

Directive:

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...