Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS trims leading zeros in model, while view/input value still remains unchanged?

Tags:

angularjs

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

like image 668
msapkal Avatar asked Jan 13 '15 06:01

msapkal


2 Answers

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

    }
});
like image 164
msapkal Avatar answered Nov 15 '22 16:11

msapkal


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.

like image 23
Ved Avatar answered Nov 15 '22 18:11

Ved