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?

4

1 回答 1

1

根据提供的评论,我最终编写了一个自定义指令。该指令适用于我的特定情况,但我不确定它是否适合其他任何人。它只是将任何模型值格式化为带有两位小数的数字,如果输入的值为 NaN,则将 0 应用于模型。(是的,它完全取决于模型变量是某种可解析的数字,但这是一个快速的 n' 脏修复。)

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;
            });
        }
    };
});

这是被引导的输入模型:

<input type="text" min="0" format-number ng-pattern="/^[0-9]+(\.[0-9]{2})?$/" ng-model="payment.JCPendingPaymentAmount" />
于 2014-05-08T16:01:56.903 回答