AngularJS formatter - how to display blank instead

2019-08-09 06:02发布

问题:

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