Currency mask, what's wrong?! Solved


#1

I’m trying to use this currency mask that i found on the internet, by it doesn’t work in ionic/ angular js.
I’m a new bee on both angularjs and ionic development , maybe it could be easier for someone of you, but this problem is freaking me out.

The error that i’m getting is:

TypeError: elem.priceFormat is not a function

Check de code that i’m using:

i’m creating a directive like this, and the problem happens when calling the priceFormat method;

    angular.module("starter.dir",[]).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;
                });
            }
        };
    }])
(function($){$.fn.priceFormat=function(options){var defaults={prefix:'US$ ',suffix:'',centsSeparator:'.',thousandsSeparator:',',limit:false,centsLimit:2,clearPrefix:false,clearSufix:false,allowNegative:false,insertPlusSign:false};var options=$.extend(defaults,options);return this.each(function(){var obj=$(this);var is_number=/[0-9]/;var prefix=options.prefix;var suffix=options.suffix;var centsSeparator=options.centsSeparator;var thousandsSeparator=options.thousandsSeparator;var limit=options.limit;var centsLimit=options.centsLimit;var clearPrefix=options.clearPrefix;var clearSuffix=options.clearSuffix;var allowNegative=options.allowNegative;var insertPlusSign=options.insertPlusSign;if(insertPlusSign)allowNegative=true;function to_numbers(str){var formatted='';for(var i=0;i<(str.length);i++){char_=str.charAt(i);if(formatted.length==0&&char_==0)char_=false;if(char_&&char_.match(is_number)){if(limit){if(formatted.length<limit)formatted=formatted+char_}else{formatted=formatted+char_}}}return formatted}function fill_with_zeroes(str){while(str.length<(centsLimit+1))str='0'+str;return str}function price_format(str){var formatted=fill_with_zeroes(to_numbers(str));var thousandsFormatted='';var thousandsCount=0;if(centsLimit==0){centsSeparator="";centsVal=""}var centsVal=formatted.substr(formatted.length-centsLimit,centsLimit);var integerVal=formatted.substr(0,formatted.length-centsLimit);formatted=(centsLimit==0)?integerVal:integerVal+centsSeparator+centsVal;if(thousandsSeparator||$.trim(thousandsSeparator)!=""){for(var j=integerVal.length;j>0;j--){char_=integerVal.substr(j-1,1);thousandsCount++;if(thousandsCount%3==0)char_=thousandsSeparator+char_;thousandsFormatted=char_+thousandsFormatted}if(thousandsFormatted.substr(0,1)==thousandsSeparator)thousandsFormatted=thousandsFormatted.substring(1,thousandsFormatted.length);formatted=(centsLimit==0)?thousandsFormatted:thousandsFormatted+centsSeparator+centsVal}if(allowNegative&&(integerVal!=0||centsVal!=0)){if(str.indexOf('-')!=-1&&str.indexOf('+')<str.indexOf('-')){formatted='-'+formatted}else{if(!insertPlusSign)formatted=''+formatted;else formatted='+'+formatted}}if(prefix)formatted=prefix+formatted;if(suffix)formatted=formatted+suffix;return formatted}function key_check(e){var code=(e.keyCode?e.keyCode:e.which);var typed=String.fromCharCode(code);var functional=false;var str=obj.val();var newValue=price_format(str+typed);if((code>=48&&code<=57)||(code>=96&&code<=105))functional=true;if(code==8)functional=true;if(code==9)functional=true;if(code==13)functional=true;if(code==46)functional=true;if(code==37)functional=true;if(code==39)functional=true;if(allowNegative&&(code==189||code==109))functional=true;if(insertPlusSign&&(code==187||code==107))functional=true;if(!functional){e.preventDefault();e.stopPropagation();if(str!=newValue)obj.val(newValue)}}function price_it(){var str=obj.val();var price=price_format(str);if(str!=price)obj.val(price)}function add_prefix(){var val=obj.val();obj.val(prefix+val)}function add_suffix(){var val=obj.val();obj.val(val+suffix)}function clear_prefix(){if($.trim(prefix)!=''&&clearPrefix){var array=obj.val().split(prefix);obj.val(array[1])}}function clear_suffix(){if($.trim(suffix)!=''&&clearSuffix){var array=obj.val().split(suffix);obj.val(array[0])}}$(this).bind('keydown.price_format',key_check);$(this).bind('keyup.price_format',price_it);$(this).bind('focusout.price_format',price_it);if(clearPrefix){$(this).bind('focusout.price_format',function(){clear_prefix()});$(this).bind('focusin.price_format',function(){add_prefix()})}if(clearSuffix){$(this).bind('focusout.price_format',function(){clear_suffix()});$(this).bind('focusin.price_format',function(){add_suffix()})}if($(this).val().length>0){price_it();clear_prefix();clear_suffix()}})};$.fn.unpriceFormat=function(){return $(this).unbind(".price_format")};$.fn.unmask=function(){var field=$(this).val();var result="";for(var f in field){if(!isNaN(field[f])||field[f]=="-")result+=field[f]}return result}})(jQuery)

Creating the input:

 <div ng-controller="fessCntrl">Example
      <input type="text" ng-model="test" format="number" /> <pre>{{test|json}}</pre>

    </div>

Starting the input’s value with like this:

.controller('fessCntrl', function ($scope) {
  $scope.test = 0;

})

Please, if someone know how to solve this, let me know.
Thanks


#4

Guys, i made some modifications in code, and now it is working properly.

here it goes the code that i’m using:

the directive module:

angular.module("starter.dir", ['starter.filter'])
    .directive('format', function ($filter) {
        return {
            require: 'ngModel',
            link: function (scope, element, attrs, ctrl) {
                if (!ctrl) return;

                element.bind("keyup", function () {
                    var result = $filter('currency')(ctrl.$viewValue, {
                                                                    prefix: 'R$ ',
                                                                    centsSeparator: ',',
                                                                    thousandsSeparator: '.'
                                                                });
                    ctrl.$setViewValue(result);
                    ctrl.$render();
                })

            }
        };
    });

the currency filter:

angular.module("starter.filter", []).filter('currency', function () {

    return function (input, options) {

        var defaults =
        {
            prefix: 'US$ ',
            suffix: '',
            centsSeparator: '.',
            thousandsSeparator: ',',
            limit: false,
            centsLimit: 2,
            clearPrefix: false,
            clearSufix: false,
            allowNegative: false,
            insertPlusSign: false,
            clearOnEmpty: false
        };

        var options = $.extend(defaults, options);


        return price_it(input, options);
    }


    // skip everything that isn't a number
    // and also skip the left zeroes
    function to_numbers(str, limit) {

        //  var value = '';
        var is_number = /[0-9]/;
        var formatted = '';
        for (var i = 0; i < (str.length); i++) {
            char_ = str.charAt(i);
            if (formatted.length == 0 && char_ == 0) char_ = false;

            if (char_ && char_.match(is_number)) {
                if (limit) {
                    if (formatted.length < limit) formatted = formatted + char_;
                }
                else {
                    formatted = formatted + char_;
                }
            }
        }

        return formatted;
    }

    // format to fill with zeros to complete cents chars
    function fill_with_zeroes(str, centsLimit) {

        while (str.length < (centsLimit + 1)) str = '0' + str;
        return str;
    }

    // format as price
    function price_format(str, ignore, options) {


        // load the pluggings settings
        var prefix = options.prefix;
        var suffix = options.suffix;
        var centsSeparator = options.centsSeparator;
        var thousandsSeparator = options.thousandsSeparator;
        var limit = options.limit;
        var centsLimit = options.centsLimit;
        var clearPrefix = options.clearPrefix;
        var clearSuffix = options.clearSuffix;
        var allowNegative = options.allowNegative;
        var insertPlusSign = options.insertPlusSign;
        var clearOnEmpty = options.clearOnEmpty;

        // If insertPlusSign is on, it automatic turns on allowNegative, to work with Signs
        if (insertPlusSign) allowNegative = true;



        var retorno;
        if (!ignore && (str === '' || str == price_format('0', true, options)) && clearOnEmpty) {
            return '';
        }
        // formatting settings
        var formatted = fill_with_zeroes(to_numbers(str, limit), centsLimit);
        var thousandsFormatted = '';
        var thousandsCount = 0;

        // Checking CentsLimit
        if (centsLimit == 0) {
            centsSeparator = "";
            centsVal = "";
        }

        // split integer from cents
        var centsVal = formatted.substr(formatted.length - centsLimit, centsLimit);
        var integerVal = formatted.substr(0, formatted.length - centsLimit);

        // apply cents pontuation
        formatted = (centsLimit == 0) ? integerVal : integerVal + centsSeparator + centsVal;

        // apply thousands pontuation
        if (thousandsSeparator || $.trim(thousandsSeparator) != "") {
            for (var j = integerVal.length; j > 0; j--) {
                char_ = integerVal.substr(j - 1, 1);
                thousandsCount++;
                if (thousandsCount % 3 == 0) char_ = thousandsSeparator + char_;
                thousandsFormatted = char_ + thousandsFormatted;
            }

            //
            if (thousandsFormatted.substr(0, 1) == thousandsSeparator) thousandsFormatted = thousandsFormatted.substring(1, thousandsFormatted.length);
            formatted = (centsLimit == 0) ? thousandsFormatted : thousandsFormatted + centsSeparator + centsVal;
        }

        // if the string contains a dash, it is negative - add it to the begining (except for zero)
        if (allowNegative && (integerVal != 0 || centsVal != 0)) {
            if (str.indexOf('-') != -1 && str.indexOf('+') < str.indexOf('-')) {
                formatted = '-' + formatted;
            }
            else {
                if (!insertPlusSign)
                    formatted = '' + formatted;
                else
                    formatted = '+' + formatted;
            }
        }

        // apply the prefix
        if (prefix) formatted = prefix + formatted;

        // apply the suffix
        if (suffix) formatted = formatted + suffix;

        return formatted;
    }


    // Formatted price as a value
    function price_it(valor, options) {
        console.log("price_it >> " + valor);

        var retorno;
        var str = valor;
        var price = price_format(str, null, options);
        if (str != price) retorno = price;
        if (parseFloat(str) == 0.0 && clearOnEmpty) retorno = '';

        return retorno;
    }

    // Add prefix on focus
    function add_prefix() {
        console.log("add_prefix");
        value(prefix + get());
    }

    function add_suffix() {
        console.log("add_suffix");
        obj.val(get() + suffix);
    }

    // Clear prefix on blur if is set to true
    function clear_prefix() {
        console.log("clear_prefix");
        if ($.trim(prefix) != '' && clearPrefix) {
            var array = get().split(prefix);
            set(array[1]);
        }
    }

    // Clear suffix on blur if is set to true
    function clear_suffix() {
        console.log("clear_suffix");
        if ($.trim(suffix) != '' && clearSuffix) {
            var array = get().split(suffix);
            set(array[0]);
        }
    }
});

Well, that’s it.
Hope it helps.
hug.


#5

Parabéns!!!
Congratulations!!!

That’s working fine for me!
Tá rodando beleza aqui!!


#6

PQP CARAAAA. Só o seu mesmo resolveu!!! eu apanhei q nem cachorro veio dessa porra. Até agora nao entendi pq nao tava funcionando no ionic. Um negocio tao simples!

Valeu!