Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: in a input how to show '$50,000.00' when no focused but show '50000' when focused?

Tags:

angularjs

I have a input to show a formatted number. Normally, when it has no focus, it should show a formmatted string, e.g. '$50,000.00'. But when it has focus, it should show the raw value, e.g. 50000 for editing.

Is there any built-in functions? Thanks!

like image 914
Zach Avatar asked May 29 '14 09:05

Zach


1 Answers

Here is a directive (formatOnBlur) which does what you want.
Note that only the element's display value is formatted (the model-value will always be unformatted).

The idea is that you register listeners for the focus and blur events and update the display value based on the focus-state of the element.

app.directive('formatOnBlur', function ($filter, $window) {
    var toCurrency = $filter('currency');

    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, elem, attrs, ctrl) {
            var rawElem = elem[0];
            if (!ctrl || !rawElem.hasOwnProperty('value')) return;

            elem.on('focus', updateView.bind(null, true));
            elem.on('blur',  updateView.bind(null, false));

            function updateView(hasFocus) {
                if (!ctrl.$modelValue) { return; }
                var displayValue = hasFocus ?
                        ctrl.$modelValue :
                        toCurrency(ctrl.$modelValue);
                rawElem.value = displayValue;
            }
            updateView(rawElem === $window.document.activeElement);
        }
    };
});

See, also, this short demo.

like image 122
gkalpak Avatar answered Oct 29 '22 16:10

gkalpak