MonOve
MonOve

Reputation: 1111

Input type number with toFixed value failing in AngularJS

I have a view tht has the following requirements:

Now, seting the value programatically as 1.20 for that value to display in the input is complicated:

Any ideas?

Upvotes: 0

Views: 977

Answers (2)

MonOve
MonOve

Reputation: 1111

Based on https://github.com/angular/angular.js/issues/5680#issuecomment-206325921 I did the following:

(function(){
    angular.module('app')
        .directive('toFixed', [function () {
            return {
                require: '^ngModel',
                link: function(scope, element, attrs, ngModel) {
                    ngModel.$formatters.push(function(value) {
                        return parseFloat(value);
                    });
                    ngModel.$render = function() {
                        var viewValue = parseFloat(ngModel.$viewValue || 0);
                        element.val(viewValue.toFixed(2));
                    }
                }
            };
        }]);
}());

Upvotes: 1

Phil Ninan
Phil Ninan

Reputation: 1198

You can take advantage of NgModel and add a parser or formatter.

function NumberFormatter($filter){
'ngInject';

return {
    restrict: 'A',
    require: '^ngModel',
    link: function(scope, element, attrs, ngModelCtrl){
          //format text going to user (model to view)
          ngModelCtrl.$formatters.push(function(value) {
             return $filter('number')(parseFloat(value) , 2);
          });

          //format text from the user (view to model)
          ngModelCtrl.$parsers.push(function(value) {
            return doParsing(value)
          });
    }
}
}

ngModel Formatters and Parsers

Upvotes: 0

Related Questions