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.
有内置功能吗?谢谢!
Is there any built-in functions? Thanks!
推荐答案
这是执行您想要的操作的指令(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);
}
};
});
另请参见此 简短演示 .
See, also, this short demo.
这篇关于AngularJS:在一个输入中,当没有聚焦时如何显示"$ 50,000.00",而在聚焦时如何显示"50000"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!