AngularJs currency in Euro [duplicate] - angularjs

How to move the symbol euro from the front of the value to after it?
Example:
{{product.price | currency : "€"}} will produce € 12.00
but I would like 12.00 €

You don't have to hack the currency filter!
AngularJS has a great support for i18n/l10n. The currency filter uses the default currency symbol from the locale service and positions it based on the locale settings.
So it's all about supporting and setting the right locale.
<script src="i18n/angular-locale_de-de.js"></script>
If you are using npm or bower all locales are available via the angular-i18n package.
<span>{{ product.price | currency }}</span>
will now produce the following output:
65,95 €
Supporting multiple localizations
If you want to support multiple localizations be careful with the currency symbol as it changes to the default currency of the used locale. But 65,95 € are different to $65,95. Provide the currency symbol as parameter to be safe:
<span>{{ product.price | currency:'€' }}</span>
In de-de the output would still be 65,95 € but if the location is eg. en-us it would be €65.95 (which is despite some other sayings the correct format to display euro prices in English).
To learn more about angular and i18n/l10n refer to the developer guide.

You can't with the currency filter. You could write your own, or just use the number filter.
{{(produce.price | number:2) + "€"}}

use this trick.
<div>{{product.price | currency : '' }} €</div>

The solutions proposed are all dirty.
at first, the filter allow change symbol by add it as parameter:
{{product.price | currency : "€"}}
but the right way is localize your app as suggested by #Andreas
if you localize your app for example with italian locale setting (it-it) inside your app you need only invoke the filter to obtain the € sign.
{{product.price | currency }}
Italian locale setting put the Euro sign before the currency value.
You could change che locale value, or much better override them as proposed in the follow linked answer:
Why AngularJS currency filter formats negative numbers with parenthesis?
you could override the locale setting put your currency symbol (\u00A4) as a prefix or suffix for positive value and negative too.
app.config(['$provide', function($provide) {
$provide.decorator('$locale', ['$delegate', function($delegate) {
if($delegate.id == 'it-it') {
$delegate.NUMBER_FORMATS.PATTERNS[1].negPre = '\u00A4\u00a0-';
$delegate.NUMBER_FORMATS.PATTERNS[1].negSuf = '';
$delegate.NUMBER_FORMATS.PATTERNS[1].posPre = '\u00A4\u00a0';
$delegate.NUMBER_FORMATS.PATTERNS[1].posSuf = '';
}
return $delegate;
}]);
}]);
so after this instruction the filter:
{{product.price | currency}}
will produce the follow output
€ 12

Angularjs has a great support for internationalization and localization.
The application of internationalization and localization depends on the scope of your application.
For example if your application only support euro then you need only the localization for euro and does not require all the currency and its formatting.
In such situation (Assuming your situation is similar to above ) you can create an app configuration and set locale as the localization you required using some decorators. A decorator function intercepts the creation of a service, allowing it to override or modify the behavior of the service.
angular
.module('app', [])
.config(['$provide', function($provide) {
$provide.decorator('$locale', ['$delegate', function($delegate) {
$delegate.NUMBER_FORMATS = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PATTERNS: [{ // Decimal Pattern
minInt: 1,
minFrac: 0,
maxFrac: 3,
posPre: '',
posSuf: '',
negPre: '-',
negSuf: '',
gSize: 3,
lgSize: 3
}, { //Currency Pattern
minInt: 1,
minFrac: 0,
maxFrac: 1,
posPre: '\u00A4',
posSuf: '',
negPre: '(\u00A4',
negSuf: ')',
gSize: 3,
lgSize: 3
}],
CURRENCY_SYM: '€'
}
return $delegate;
}]);
}])
.controller('appController', ['$scope', function($scope) {
$scope.price = 20.55;
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="appController">
Price : {{price | currency}}
</div>
</div>
The above configuration shows all possible values for decimal and currency settings.
You can change according to your requirements at app level.
If you dont want the effect to be in entire application better is to go for a directive

It's quite an old question, it's different these days.. Maybe it was back then aswell..
So if someone else finds this..
But you need to include the correct locale to get the correct currency formatting in the currency filter.
Check the angular documentation, for example dutch currency formatting is € 5,00 While english is 5,00 € and american is €5.00

I use this solution in my project (in production) in France (It must ALWAYS show 5.00€, NEVER show €5.00):
<span>Price: {{product.price| currency:""}} €</span>
DEMO
Please, read the real question of this post (Angular Js currency, symbol euro after) before downvote too quickly!!!!!

Using the locale (as explained in the answer in this thread -
at Angular Js currency, symbol euro after) seems like the most correct way to do it, but it doesn't seem to offer the flexibility to put the currency symbol or name where you want it relative to the value you're referencing to. If you need to have your currency symbol after your value, you could have a separate product.currency field and interpolate that after (or before) your price value.
So if you have product.price = 40 and product.currency = '€', you could display it as 40 € with {{product.price}} {{product.currency}}. Or € 40 by reversing the fields: {{product.currency}} {{product.price}}.
You'd probably want to format the product.price values via the decimal pipe if you did that (https://angular.io/api/common/DecimalPipe). - So "40.00 €" would be : {{product.amount | number:'2.2-2'}} {{product.currency}}.
fyi - in this case, I'd probably have a separate field product.currency and product.currencySymbol (e.g. "USD" and "$" respectively), but then you're getting more into the functionality of the locale as referenced in the other answer I link above. But if you need to place the currency name or symbol in a different location relative to the value than what Angular will let you do via its native pipes, and want to use a currency that's specific to a record or set that you're working with without hard-coding its symbol or name on the page (e.g. if you have multiple currencies you're displaying), this is one way to do it dynamically.

You can create a filter :
app.filter('euroFormat', function () {
return function (input) {
return input+' \u20AC';
};
});
and apply it on your html code with :
<span>Price: {{product.price| euroFormat}}</span>

Related

Angularjs currency format ₺ (Turkish Lira)?

How to change angularjs currency format? I need to change like this
2.543.128,76 . Default angularjs format $254,312,876.00.
you just have to add the right local like <script src="i18n/angular-locale_tr-tr.js"></script>
supported locales are here : https://github.com/angular/angular.js/tree/master/src/ngLocale
you could also do it with number filter :
{{(produce.price | number:2) + "₺"}}

How can I display the currency in Angular.js dynamically based on per-record data?

I need to be able to show the currency dynamically with the value. For a fixed currency, I was able to do:
<span id="currency-custom">{{amount | currency:'&#8377'}}</span>
But what if I wanted to change the currency based on what came from the server as well? In my controller I have:
$scope.longestRide = {
'fromAddress': 'xxx',
'toAddress': 'yyy',
'mycurrency': '₹',
'cost': '238',
'duration': '00:49:02'
}
But this does not seem to work:
<span id="currency-custom">{{amount | currency:mycurrency}}</span>
How can I display the currency based on the javascript data structure?
You should try using your filter inside ng-bing-html like this:
<span ng-bind-html="amount | currency:mycurrency"></span>

display text prefix only if data is present

I have some AngularJS code that displays an outstanding balance only if their is a balance to display.
{{Customer.LastName}}, {{Customer.FirstName}} ${{Customer.OutstandingBalance}}
What I would like to do is not display the dollar sign ($) at all if there is no outstanding balance. How do I make the dollar sign dependent on the value of Customer.OutstandingBalance?
I think except obvious suggestions like "wrap it in <span ng-show="Customer.OutstandingBalance">
you could do smth like this: {{Customer.LastName}}, {{Customer.FirstName}} {{Customer.OutstandingBalance ? '$' : ''}}{{Customer.OutstandingBalance}}
Use custom filter with inbuilt currency filer.
app.filter('myCurrency', function($filter){
return function(input){
return input ? $filter('currency')(input) : '';
};
});
in view use
{{Customer.LastName}}, {{Customer.FirstName}} {{Customer.OutstandingBalance | myCurrency}}
Here's plunker demo
http://plnkr.co/edit/ocqmiz4tNX49R8rG8VA7?p=preview
You could have a span that only is showed based on the OutstandingBalance:
<span ng-show="Customer.OutstandingBalance != 0">$</span> {{Customer.OutstandingBalance}}

Variable substitution while using messageformat with angular-translate

I'm using angular-translate with messageformat interpolation to pluralize some strings.
(for those who don't know what I'm talking about: http://angular-translate.github.io/docs/#/guide/14_pluralization).
It's going pretty well, but I can't figure out how to use variables instead of constants.
$translateProvider.translations('it', {
SELECTED_CATEGORIES: "{NUM, plural, =0{Nessuna categoria selezionata} one{1 categoria selezionata} other{# categorie selezionate}}"
}).translations('en', {
SELECTED_CATEGORIES: "{NUM, plural, =0{No category selected} one{1 selected category} other{# selected categories}}"
});
and this is the HTML code:
<span>{{ 'SELECTED_CATEGORIES' | translate:"{'NUM': 2 }" }}</span>
This works but if I use
<span>{{ 'SELECTED_CATEGORIES' | translate:"{'NUM': my_variable_in_the_scope }" }}</span>
I get an error. I tried to use quotes, double quotes and similar, but nothing seems to work.
I know that messageformat doesn't support expression evaluation, but I hoped that a variable substitution would have worked.
Any Idea?
Well, the correct solution should be passing the scope and accessing the value within the messageFormat code.
You can do this easily like this:
$translateProvider.translations('it', {
SELECTED_CATEGORIES: "{my_variable_in_the_scope , plural, =0{Nessuna categoria selezionata} one{1 categoria selezionata} other{# categorie selezionate}}"
}).translations('en', {
SELECTED_CATEGORIES: "{my_variable_in_the_scope , plural, =0{No category selected} one{1 selected category} other{# selected categories}}"
});
And your HTML:
<span>{{ 'SELECTED_CATEGORIES' | translate:your_scope }}</span>
Please note: I passed "your_scope" within the translate-filter and accessed "my_variable_in_the_scope" within the messageFormat code.
This should be the best solution.
To use variables in angular filters, you have to use
filter:{key: value} without quotes
E.g. my filter replaceVariable is used to enable rails yml placeholders being replaced with a js variable
usage:
{{ sometranslation | replaceVariable:{count:results} }}
filter:
// replaces {%count} in yml translations to work with angular
filters.filter('replaceVariable', function () {
"use strict";
return function (string, variable) {
var replace = string.replace(/%\{[\w\s]*\}/, variable.count);
return replace;
};
});
so i guess with translate you have to use it the same way. I remember i couldnt get this to work either which is why i chain my custom filter after
somevalue | translate | myCustomFilter

How to extend or override existing filters in angularjs?

Is it possible to extend existing "standard" filters (date, number, lowercase etc)?
In my case I need to parse date from YYYYMMDDhhmmss format so I'd like to extend (or override) date filter instead of writing my own.
I prefer to implement the decorator pattern, which is very easy in AngularJS.
If we take #pkozlowski.opensource example, we can change it to something like:
myApp.config(['$provide', function($provide) {
$provide.decorator('dateFilter', ['$delegate', function($delegate) {
var srcFilter = $delegate;
var extendsFilter = function() {
var res = srcFilter.apply(this, arguments);
return arguments[2] ? res + arguments[2] : res;
}
return extendsFilter;
}])
}])
And then in your views, you can use both.. the standard output and the extended behavior. with the same filter
<p>Standard output : {{ now | date:'yyyyMMddhhmmss' }}</p>
<p>External behavior : {{ now | date:'yyyyMMddhhmmss': ' My suffix' }}</p>
Here is a working fiddle illustrating both techniques:
http://jsfiddle.net/ar8m/9dg0hLho/
I'm not sure if I understand your question correctly, but if you would like to extend functionality of existing filters you could create a new filter that decorates an existing one. Example:
myApp.filter('customDate', function($filter) {
var standardDateFilterFn = $filter('date');
return function(dateToFormat) {
return 'prefix ' + standardDateFilterFn(dateToFormat, 'yyyyMMddhhmmss');
};
});
and then, in your template:
{{now | customDate}}
Having said the above, if you simply want to format a date according to a given format this can be done with the existing date filter:
{{now | date:'yyyyMMddhhmmss'}}
Here is the working jsFiddle illustrating both techniques: http://jsfiddle.net/pkozlowski_opensource/zVdJd/2/
Please note that if a format is not specified AngularJS will assume that this is 'medium' format (the exact format depends on a locale). Check http://docs.angularjs.org/api/ng.filter:date for more.
The last remark: I'm a bit confused about the 'parse from' part of your question. The thing is that filters are used to parse an object (date in this case) to string and not vice verse. If you are after parsing strings (from an input) representing dates you would have to look into NgModelController#$parsers (check the "Custom Validation" part in http://docs.angularjs.org/guide/forms).

Resources