Angular, input field with a currency mask directive for money format on the fly

前端 未结 5 1877
被撕碎了的回忆
被撕碎了的回忆 2020-12-04 18:10

I\'m trying to create an input mask for a EU money field using http://jquerypriceformat.com/

So far in my directive, the input shows correctly to the user with the

5条回答
  •  再見小時候
    2020-12-04 19:11

    From your example I don't see that link returns something.

    I would write directive something like:

    .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) {
    
              elem.priceFormat({
                prefix: '',
                centsSeparator: ',',
                thousandsSeparator: '.'
            });                
    
                    return elem[0].value;
                });
            }
        };
    }]);
    

    Demo 1 Fiddle

    enter image description here

    If you want on start fire the filter, use $formatters:

    Now link is:

    link: function (scope, elem, attrs, ctrl) {
                if (!ctrl) return;
    
                var format = {
                        prefix: '',
                        centsSeparator: ',',
                        thousandsSeparator: ''
                    };
    
                ctrl.$parsers.unshift(function (value) {
                    elem.priceFormat(format);
    
                    return elem[0].value;
                });
    
                ctrl.$formatters.unshift(function (value) {
                    elem[0].value = ctrl.$modelValue * 100 ;
                    elem.priceFormat(format);
                    return elem[0].value;
                })
            }
    

    Demo 2 Fiddle

提交回复
热议问题