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

后端 未结 5 796
遥遥无期
遥遥无期 2020-12-09 19:05

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

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 19:41

    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.

提交回复
热议问题