我正在使用Angular指令,该指令使用逗号格式化输入字段数字。我也希望这个过滤器自动插入美分的十进制数。每个数字都将包含美分。例如,如果我想在输入字段中输入$ 1,000.00,则必须输入100000.我做了一个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;
});
}
};
}]);
答案 0 :(得分:3)
大概是这样的吗?
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 强>