【发布时间】:2017-10-17 00:26:25
【问题描述】:
我创建了一个 Angular 指令,用于在用户输入美元金额时为输入框格式化美元金额。理想情况下,金额将始终格式化为模糊的小数点后 2 位。例如,3 将返回 3.00,1.1 将返回 1.10,依此类推。但是,当我输入诸如 1.01 之类的金额时,它会返回 1.010,这并不理想,因为它会添加额外的小数位。有人知道我错过了什么吗?
这是指令的代码
'use strict';
angular.module('edAssistApp').directive('format', ['$filter', function($filter) {
return {
require: '?ngModel',
link: function ($scope, $elem, $attrs, $ctrl) {
var formatType = $attrs.format.split(':')[0];
var formatParam = $attrs.format.split(':')[1];
if (!$ctrl) {
return;
}
$ctrl.$formatters.unshift(function (a) {
return $filter($attrs.format)($ctrl.$modelValue);
});
// This will parse the value that was put in and format to a currency number
// (i.e., 1234.56). First it determines if the number is valid (isNaN),
// then it will truncate the number down to 2 decimal points (... * 100 / 100),
// then it will convert it to a string and split by the '.' (if there is one),
// if the decimal is < 10, add a 0 so it will always have 2 digits.
$elem.bind('blur', function(event) {
var outputVal = '';
if (!isNaN(parseFloat($elem.val()))) {
var parsedNumber = Math.round(parseFloat($elem.val()) * 100) / 100;
var p2dec = parsedNumber.toString().split('.')[1] || 0;
if (p2dec < 10) {
p2dec += '0';
}
outputVal = [parsedNumber.toString().split('.')[0], p2dec].join('.');
}
$elem.val($filter(formatType, formatParam)(outputVal));
$ctrl.$setViewValue(outputVal);
$ctrl.$render();
});
}
};
}]);
【问题讨论】:
标签: angularjs input number-formatting