AngularJS formatter - how to display blank instead of zero

限于喜欢 提交于 2019-12-11 07:58:18

问题


Please see this previous question: Format input value in Angularjs

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.

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

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.


回答1:


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

here is working JSFIDDLE



来源:https://stackoverflow.com/questions/25599184/angularjs-formatter-how-to-display-blank-instead-of-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!