Mahesh Sapkal Mahesh Sapkal - 1 year ago 180
AngularJS Question

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

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"/>


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download