Arti
Arti

Reputation: 7762

Angular material input number change format

In my angular-material app I have a field with validation:

<input type="number" ng-model="myValue"
       name="myValue" 
       min="0" max="100" 
       ng-pattern="/^[0-9]\d*(\.\d+)?$/" required>

It works fine. But now I need to make it to allow user to type .75 and get instead of 0.75

So the question how to apply my filter:

if( myValue.substring(0,1) == "." ){
    myValue = "0" + myValue;
}

before angular material ng-pattern and type="number" validation

Upvotes: 1

Views: 2274

Answers (1)

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

You can write some directive with $filter, $formatters and $parsers:

app.directive('parser', ['$filter',
    function($filter) {
        return {
            restrict:'A',
            require: 'ngModel',
            link: function(scope, element, attrs, ctrl) {

                ctrl.$formatters.unshift(function (a) {
                return $filter('myFilter')(ctrl.$modelValue)
            });

             ctrl.$parsers.unshift(function (viewValue) {
             element[0].value = $filter('myFilter')(element[0].value);
             return element[0].value;
            });
            }
        };
    }
]);

app.filter('myFilter', [
    function() {
        return function(input) {

           if( input && input.substring(0,1) == "." ){
             input = "0" + input;
           }
            return input;
        };
    }
]);

DEMO Plunkr


However you cannot use type number because as I remember . not supported and doesn't parses as integer

Hope it will give you direction

Upvotes: 1

Related Questions