9

For an input element with type number, when the number entered has leading zeros like '0000123456', the model is updated to 123456, while the view/input still remains the same 0000123456.

However if I switch from number to text everything works as expected. I would like to have number since it would display numeric keyboard for mobile devices.

<input type="number" ng-model="vm.orderid"/>
{{vm.orderid}}

PLUNKR

msapkal
  • 8,268
  • 2
  • 31
  • 48
  • possible duplicate of [How to do two-way filtering in angular.js?](http://stackoverflow.com/questions/11616636/how-to-do-two-way-filtering-in-angular-js) – Steve Mitcham Jan 13 '15 at 06:45
  • Thanks for the info. What would I like to have is if the model is updated why the input fields is not updated and still has the wrong value ? – msapkal Jan 13 '15 at 06:52
  • use input type ="tel".. – Ved Jan 13 '15 at 07:05
  • The binding model in angular by default only pushes things through when a change occurs, so the parser fires only when the UI changes and the formatter fires only when the model changes. – Steve Mitcham Jan 13 '15 at 17:40

2 Answers2

5

As stated by @Steve, I used a custom directive my-decimals which matches the view value with the model when input losses the focus.

<input type="number" my-decimals ng-model="vm.orderid"/>

angular.directive('myDecimals', function() {
    return {
        require: 'ngModel',
        link: function(scope, elm, attrs, ctrl) {

            elm.blur(function() {
                var val = ctrl.$viewValue;
                ctrl.$setViewValue(val * 1);
                ctrl.$render();
            });
        }

    }
});
Tom Kidd
  • 12,830
  • 19
  • 89
  • 128
msapkal
  • 8,268
  • 2
  • 31
  • 48
  • Is there a missing closing curly bracket? Can't get this directive to work! [link] (http://stackoverflow.com/questions/30303191/leading-zeros-missing-within-number-input) – Al Ex Tsm May 19 '15 at 07:10
  • Your welcome, but I haven't been able to get it working. Just won't trigger.. :/ – Al Ex Tsm May 19 '15 at 12:18
3

You have to options for this,
use: <input type = "tel">
it has been introduced for this exact purpose. It's one of the new input types in HTML5.

or, <input type="text" pattern="[0-9]">
It Will bring up the numeric keypad on iPhone and the Android phones.You can test this. I am not 100%sure.

Ved
  • 11,837
  • 5
  • 42
  • 60