Reputation: 6155
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!
Upvotes: 1
Views: 1786
Reputation: 93
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 }}
Upvotes: 0
Reputation: 6155
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!
Upvotes: 0
Reputation: 49590
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("£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)
Upvotes: 1
Reputation: 1856
You could just have the following in your HTML, taking advantage of the filter directive:
<div>
<span>{{ amount | currency : '£' }}</span>
</div>
Upvotes: 0