AngularJS:在输入中如何在没有聚焦时显示“$50,000.00"但在聚焦时显示“50000"? [英] AngularJS: in a input how to show '$50,000.00' when no focused but show '50000' when focused?
问题描述
我有一个输入来显示一个格式化的数字.通常,当它没有焦点时,它应该显示一个格式化的字符串,例如'$50,000.00'.但是当它有焦点时,它应该显示原始值,例如50000 用于编辑.
I have a input to show a formatted number. Normally, when it has no focus, it should show a formmatted string, e.g. '$50,000.00'. But when it has focus, it should show the raw value, e.g. 50000 for editing.
有内置函数吗?谢谢!
推荐答案
这是一个指令 (formatOnBlur
),它可以满足您的需求.
请注意,只有元素的显示值被格式化(模型值将始终未格式化).
Here is a directive (formatOnBlur
) which does what you want.
Note that only the element's display value is formatted (the model-value will always be unformatted).
这个想法是为 focus
和 blur
事件注册监听器,并根据元素的焦点状态更新显示值.
The idea is that you register listeners for the focus
and blur
events and update the display value based on the focus-state of the element.
app.directive('formatOnBlur', function ($filter, $window) {
var toCurrency = $filter('currency');
return {
restrict: 'A',
require: '?ngModel',
link: function (scope, elem, attrs, ctrl) {
var rawElem = elem[0];
if (!ctrl || !rawElem.hasOwnProperty('value')) return;
elem.on('focus', updateView.bind(null, true));
elem.on('blur', updateView.bind(null, false));
function updateView(hasFocus) {
if (!ctrl.$modelValue) { return; }
var displayValue = hasFocus ?
ctrl.$modelValue :
toCurrency(ctrl.$modelValue);
rawElem.value = displayValue;
}
updateView(rawElem === $window.document.activeElement);
}
};
});
<小时>
另请参阅此简短演示.
这篇关于AngularJS:在输入中如何在没有聚焦时显示“$50,000.00"但在聚焦时显示“50000"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!