AngularJS格式化 - 如何显示空白,而不是零 [英] AngularJS formatter - how to display blank instead of zero

查看:848
本文介绍了AngularJS格式化 - 如何显示空白,而不是零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅此previous问题:
在Angularjs 格式输入值

Please see this previous question: Format input value in 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.

小提琴指令code:

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;
            });
        }
    };
}]); 

我想AP preciate如何改变了小提琴的指令,这样你就不必打两次退格键清除输入的任何建议。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆