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

后端 未结 5 778
遥遥无期
遥遥无期 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条回答
  •  -上瘾入骨i
    2020-12-09 19:26

      angular.module('app', [])
            .controller('TestCntrl', function TestCntrl($scope) {
                $scope.value = 50000.23;
            })
            .directive('numberFormatter', ['$filter', function ($filter) {
                return {
                    restrict: 'A',
                    require: 'ngModel',
                    scope: { 'decimal': '=decimal' },
                    link: function (scope, element, attr, ngModel) {
                        ngModel.$parsers.push(whatToSet);
                        ngModel.$formatters.push(whatToShow);
                        element.bind('blur', function () {
                            element.val(whatToShow(ngModel.$modelValue, scope.decimal))
                        });
                        element.bind('focus', function () {
                            element.val(ngModel.$modelValue);
                        });
                        function whatToSet(str) {
                            var num = 0
                            var numbe = num !== undefined ? num : 0;
                            var strr = str.toString();
                            strr = strr.replace(',', '.');
                            numbe = parseFloat(strr);
                            return numbe;
                        }
                        function whatToShow(num) {
                            if (num) {
                                return '$' + $filter('number')(num, scope.decimal);
                            } else {
                                return '';
                            }
                        };
                    }
                };
            }]);
    
    
    
    
    
    
        
    value in the model: {{value}}

提交回复
热议问题