1

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.

2
  • a tad confusing. i would refphrase. this your question is being examined for closing for being too vague or offtopic. Commented Sep 1, 2014 at 14:15
  • 1
    I have edited the question to try to make it clearer. In truth this would have been better as a comment to the previous question but I did not have enough to rep to comment on that question. I will go back and add an answer to the previous question with a link to the fiddle provided by wickY26. Commented Sep 2, 2014 at 2:15

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @wickY26! I had tried a simple if but obviously missed something.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.