AngularJS 格式化程序 - 如何显示空白而不是零 [英] AngularJS formatter - how to display blank instead of zero
问题描述
请参阅上一个问题:在 Angularjs 中格式化输入值
我遇到的问题是(就像上面问题的答案中的小提琴一样,即 http://jsfiddle.net/SAWsA/811/),在输入中剩余的单个数字上按退格键会导致出现零而不是清除输入.
The issue I am having is that (as is the case in the fiddle in the answer to the question above, i.e. http://jsfiddle.net/SAWsA/811/), hitting backspace on a single number remaining in the input leads to a zero appearing rather than clearing the input.
小提琴指令代码:
fessmodule.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;
});
}
};
}]);
对于如何更改小提琴中的指令以便您不必按两次退格键来清除输入的任何建议,我将不胜感激.
I would appreciate any suggestions for how to alter the directive in the fiddle so that you don't have to hit backspace twice to clear the input.
推荐答案
你可以简单地将一个 if-else 条件添加到你的指令中,它就完成了...
you can simply put an if-else condition to your directive and it is done...
ctrl.$parsers.unshift(function (viewValue) {
console.log(viewValue);
if(viewValue){
var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
elem.val($filter('number')(plainNumber));
return plainNumber;
}else{
return '';
}
});
这里正在运行 JSFIDDLE
这篇关于AngularJS 格式化程序 - 如何显示空白而不是零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!