2

I have an input that uses ng-pattern like so:

<input type="text" min="0" ng-pattern="/^[0-9]+(\.[0-9]{2})?$/" ng-model="payment.amount" />

However, if I try and change my payment.amount in scope, like so:

$scope.payment.amount = 150.5;

It fails to bind. Note the regex - if the amount has a decimal place, it must include two digits after it. If it doesn't, it fails validation.

See obligatory plunker: http://plnkr.co/edit/TIltn1NEHdN3so6GnTQi?p=preview

The Question: how can I get it to bind correctly, preferably with a 0 at the end of the number?

  • How about writing your own custom directive for that? You can check for the number of digits in the directive and use it to show or hide amount. For now ng-pattern won't even recognize for digits after decimal ending with zero.. (eg: 15.40 will be read as 15.4). I personally think creating custom directive would be concise and easy. – javaCity May 06 '14 at 22:19

1 Answers1

1

I ended up writing a custom directive, per the comment provided. The directive works for my particular situation, but I'm not sure it's going to fit perfectly for anyone else. It simply formats any model value as a number with a two digit decimal and applies 0 to the model if the value being input is NaN. (Yes, it's wholly dependent on the model variable being some kind of parsable number, but this is a quick n' dirty fix.)

angular.module("app").directive('formatNumber', function ($timeout) {
    return {
        require: '?ngModel',
        scope: {
            bindModel: '=ngModel'
        },
        link: function (scope, element, attr, ngModel) {
            ngModel.$formatters.push(function (v) {
                return parseFloat(ngModel.$modelValue).toFixed(2);
            });

            ngModel.$parsers.push(function (v) {
                var presumedVal = parseFloat(ngModel.$viewValue);
                if (_.isNaN(presumedVal)) {
                    return 0;
                }
                return presumedVal;
            });
        }
    };
});

Here is the input model being directed:

<input type="text" min="0" format-number ng-pattern="/^[0-9]+(\.[0-9]{2})?$/" ng-model="payment.JCPendingPaymentAmount" />