angular.js - wrapping the currency symbol and decimal numbers in spans

南笙酒味 提交于 2019-12-03 11:18:53
zs2020

You can create a custom filter

app.filter('euro', function () {
    return function (text) {
        text = text.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1 ");
        var t = text + '<span class="desc">,00</span><span class="cur">€</span>';
        return t;
    };
});

<span ng-bind-html-unsafe="1000000 | euro"></span>

The result will be

1 000 000,00€

Working Demo

(The regex is posted by @Paul Creasey in his answer https://stackoverflow.com/a/1990554/304319)

It's actually possible to do this

<p ng-bind-html-unsafe="10000 | currency:'<span>$</span>'"></p>

or wrap it around the native currency filter like this

app.filter('currencys', ['$filter', '$locale', 
    function($filter, $locale) {
        return function (num) {
            var sym = $locale.NUMBER_FORMATS.CURRENCY_SYM;
            return $filter('currency')(num, '<span>'+ sym +'</span>');
        };
    }
]);

and then use it like this

<span ng-bind-html-unsafe="10000 | currencys"></span>

Some locales have the currency sign prefixed, some postfixed, e.g. "one hundred euros" would be rendered "€ 100" or "100 €". What then?

If you don't mind doing some parsing, however read on:

The $locale service contains the symbols required for currency formatting:

$locale.NUMBER_FORMATS.CURRENCY_SYM
$locale.NUMBER_FORMATS.DECIMAL_SEP

(And there is more detailed info in $locale.NUMBER_FORMATS.PATTERNS[] - the value at position [1] is for currencies)

You could create a directive that uses the currency filter to obtain the initial formatted string, e.g. "1 000 000,50 €" then search for $locale.NUMBER_FORMATS.CURRENCY_SYM and replace it with <span>{{ $locale.NUMBER_FORMATS.CURRENCY_SYM }}</span>, do something similar for the decimal separator and then set the innerHTML of an element.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!