Format input value in Angularjs

Solution 1:

Here is working example where we use unshift:

angular.module('myApp.directives', []).directive('format', ['$filter', function ($filter) {
    return {
        require: '?ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;


            ctrl.$formatters.unshift(function (a) {
                return $filter(attrs.format)(ctrl.$modelValue)
            });


            ctrl.$parsers.unshift(function (viewValue) {
                var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
                elem.val($filter(attrs.format)(plainNumber));
                return plainNumber;
            });
        }
    };
}]);

The HTML seems:

<input type="text" ng-model="test" format="number" />

See Demo Fiddle

Hope its help

Solution 2:

This module works fine for me.

https://github.com/assisrafael/angular-input-masks

Example:

<input type="text" name="field" ng-model="number" ui-number-mask>