1
我有一個創建的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();
});
}
};
}]);