2

I am using a Angular directive that formats input fields numbers with commas. I would also like this filter to automatically insert the decimal for cents.Every number will always have cents involved. For example if I wanted to put $1,000.00 in a input field i would have to type 100000. I made a plunkr but cant get the angular working

plunkr

app.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('number')(plainNumber));
            return plainNumber;
        });
    }
};
 }]);

1 Answer 1

3

Probably like this?

ctrl.$parsers.unshift(function (viewValue) {
    var plainNumber = viewValue.replace(/[^\d|\-+]/g, ''); //replace even dot and comma
    elem.val($filter('number')(plainNumber/100 , 2)); //use number filter with 2 decimal places and divide the number by 100
    return plainNumber;
});

Plnkr

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.