4

我正在寻找一种将input元素格式化为货币格式的方法。具体来说,我想要数千个逗号。

最初的解决方案是仅格式化控制器中的值并将其返回给视图。但是为了做我的计算,我必须再次把所有这些都去掉。然后我遇到$formatters$parsersfor ngModelController。本质上,它允许您创建管道功能。第一个为用户格式化值。第二个解析要在控制器中使用的值。正是我想要的。

我的解决方案只适用于页面加载。看看我的小提琴

myApp.directive('thousandsformatter', function ($filter) {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ctrl) {
            ctrl.$formatters.push(function (data) {
                var formatted = $filter('currency')(data);
                console.log(formatted);
                //convert data from model format to view format
                return formatted; //converted
            });
            ctrl.$parsers.push(function (data) {
                console.log(data);
                //convert data from view format to model format
                return data; //converted
            });
        }
    };
});

我怎样才能让它随着用户输入而更新?

4

1 回答 1

4

我已经对 parse 函数进行了调整,现在它可以按照您的意愿工作了。

myApp.directive('thousandsformatter', function ($filter) {
    var precision = 2;
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ctrl) {
            ctrl.$formatters.push(function (data) {
                var formatted = $filter('currency')(data);
                console.log(formatted);
                //convert data from model format to view format
                return formatted; //converted
            });
            ctrl.$parsers.push(function (data) {
                var plainNumber = data.replace(/[^\d|\-+|\+]/g, '');
                var length = plainNumber.length;
                var intValue = plainNumber.substring(0,length-precision);
                var decimalValue = plainNumber.substring(length-precision,length)
                var plainNumberWithDecimal = intValue + '.' + decimalValue;
                //convert data from view format to model format
                var formatted = $filter('currency')(plainNumberWithDecimal);
                element.val(formatted);

                return Number(plainNumberWithDecimal);
            });
        }
    };
});

在 fiddle 上查看我的解决方案

希望它有所帮助。

干杯

于 2014-03-27T03:56:50.113 回答