简体   繁体   中英

How to display currency symbol using Javascript and Angular

I am in the process of learning Angular and am having trouble displaying a currency symbol.

I am calling my data from an api which is returning a formatted entry like this:

"currency_formatted": "£20 Million"

In angular when I populate the formatted field: {{currency_formatted}} it outputs:

 £20 Million

What I am expecting is: £20 Million

I can have the currency symbol returned in the api so: GBP, is there a way to use this to have the correctly formatted currency instead of passing the hex?

Any ideas would be appreciated!

The hex is an HTML-encoded value. You can HTML decode using the ng-bind-html directive, for example:

<span ng-bind-html="amount"></span>

This needs to be sanitized to prevent exploits. To do so, you would need to add a dependency on 'ngSanitize' , or use $sce to trust this as HTML:

$scope.amount = $sce.trustAsHtml("&#xa3;20 Million");

===

If, however, you can structure your amount into nominal value and currency symbol:

$scope.amount = {value: 20000000, symbol: '£'};

then you could is to use the currency filter to display the amount:

<span>{{amount.value | currency: amount.symbol:0}}</span>

This will display "£20,000,000" - not "£20 Million" (so, may not be what you need)

AngularJS

You could just have the following in your HTML, taking advantage of the filter directive:

<div>
   <span>{{ amount | currency : '£' }}</span>
</div>

I figured this out with the help of a friend and with New Dev's answer above. This is what I have done:

In my HTML:

<span ng-bind-html="currency_formatted | safeHtml"></span>

Then in my app I wrote a custom filter:

//Filter to use html from the api
app.filter('safeHtml', function($sce) {
    return function(unsafeHtml) {
        console.log(unsafeHtml);
        return $sce.trustAsHtml(unsafeHtml);
    }
})

Now this returns the html to be inserted into the page.

What was happening before was that Angular was sanitizing the result and escaping the & sign...

Hope this helps someone!

You can make a filter using toLocaleString like :

Number(data).toLocaleString('en', { style: 'currency', currency: 'EUR', maximumFractionDigits: 0})

Filter example :

.filter('EuroCurrency', function() {
    return function(data) {
        if (null != data) {
            return Number(data).toLocaleString('en', { style: 'currency', currency: 'EUR', maximumFractionDigits: 0});
        } else {
            return Number(0).toLocaleString('en', { style: 'currency',currency: 'EUR', maximumFractionDigits: 0});
        }
    };
});

Usage :

{{ rent | EuroCurrency }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM