21

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.

Jason
  • 2,451
  • 2
  • 23
  • 31
  • See http://stackoverflow.com/a/12947995/215945 for examples of how to build a custom validator. – Mark Rajcok Mar 21 '13 at 18:17
  • I don't see how that would help me. I'm not just trying to stop data from getting into the model...but from even appearing on the screen. I want to implement input type=number by using type=text with a directive – Jason Mar 21 '13 at 18:33
  • I'm sorry that wasn't too helpful. A $parser can be used to filter what shows in the input textbox. Please see the plunker I wrote in my answer. – Mark Rajcok Mar 21 '13 at 19:40

4 Answers4

43

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.

Community
  • 1
  • 1
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • "I looked at ng-pattern, but it does not filter what is shown in the textbox" - exactly....I'll give this a try and see what how it works...thanks for the help! – Jason Mar 22 '13 at 13:10
  • 1
    This did not work for me, I had to add as very first line in function fromUser following code if (text === undefined) return text; – epitka Nov 26 '13 at 21:24
  • 1
    @MarkRajcok - after using angular with more frequency it dawned on me I could make this even more usable as a "filtered-input" directive that takes the regex as an attribute :-) – Jason Mar 23 '14 at 16:50
  • What if I wanted to add 2 directives to an input - each adding to modelCtrl.$parsers by push()? It seems only the "ladder" is being executed in that case. – Matthias Max Aug 26 '14 at 14:03
  • Thanks for this answer, it works for me using angularjs 1.3.x. If it helps anyone I ended up adding the following to prevent the cursor from jumping to the end on invalid characters: `if(transformedInput !== inputValue) { var el = element[0]; var cursorPosition = el.selectionStart - 1; // minus one because the character entry advances the cursor position ngModelCtrl.$setViewValue(transformedInput); ngModelCtrl.$render(); el.setSelectionRange(cursorPosition, cursorPosition); }` – zai chang May 14 '15 at 10:18
  • This method removes $error.required after parsing. So, $error.required validator no longer works with this parsing method – sudhir Sep 05 '15 at 08:55
  • it works in Chrome but fails in Firefox, actually it doesn't filter anything in FF and when emptied it throws text.replace is not a function or something like that(( – Movsar Bekaev May 12 '16 at 18:56
8

HTML:

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

Directive:

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();
            }

        });
    };
});
Zyberzero
  • 1,604
  • 2
  • 15
  • 35
krish
  • 81
  • 1
  • 1
0

First include this code in js file numericInput.js

Directive : -

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

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

    };
})

HTML : -

 <input type="text" numeric />

DEMO Numeric Demo

Nishchit
  • 18,284
  • 12
  • 54
  • 81
-2

not directive but I use just:

controller:

    $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]">

it's not directive but can be used in directive as wellside

hjdud
  • 21
  • 3