0

I'm trying to change the ngModel (input type="number") Format. This code work good in angularjs 1.2.23 version as you see, but in 1.6.4 version not work. any other solution?

Output must be: 25,00

var app= angular.module('myApp',[]);
app.controller('myCtrl',function($scope){
    $scope.test=25;
})

.directive('price', function($filter) {
    return {
       restrict: 'A',
       require: '?ngModel',
       link: function(scope, element, attrs, ngModel) {
           ngModel.$formatters.push(function (value) {
                return $filter('number')(value,2);
           });
       }
    }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
    <input type="number" ng-model="test" price>
</div>

1 Answer 1

2

Input with type number requires Number not a String.

In your example return value will be a String:

ngModel.$formatters.push(function (value) {
  return $filter('number')(value,2);
});

Use parseFloat(). The parseFloat() function parses an argument and returns a floating point number. In my approach i have used step attribute which increments value for 0.01.

JSFiddle:

var app= angular.module('myApp',[]);
app.controller('myCtrl',function($scope){
    $scope.test=25;
})

.directive('price', function($filter) {
    return {
       restrict: 'A',
       require: '?ngModel',
       link: function(scope, element, attrs, ngModel) {
           ngModel.$formatters.push(function (value) {
                return parseFloat(value);
           });
       }
    }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
    <input type="number" step=".01" price ng-model="test">
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer! The output when the no decimal must be 25,00 not 25. step=".01" work when decimal but not when no decimal.
I know. Maybe someone else can resolve problem. Btw you can resolve it with input type text instead number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.