Variable substitution while using messageformat with angular-translate - angularjs

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

Related

AngularJs currency in Euro [duplicate]

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>

angular typahead fetch results with starting letter only

JS Code below :
$scope.startsWith = function(state, viewValue) {
return state.substr(0, viewValue.length).toLowerCase() == viewValue.toLowerCase();
}
html< start tag< input name="states" id="states" type="text" placeholder="Search Countries..." ng-model="selected" typeahead="state.COUNTRY_CODE as state.COUNTRY_DESC for state in states | filter:$viewValue:statestartsWith | limitTo:8">
This is still not searching for first letter, it is giving results matching in middle of the string also. Please help
The order of filters are incorrect.
typeahead="state.COUNTRY_CODE as state.COUNTRY_DESC for state in states | startsWith:$viewValue | limitTo:8"
In order to make it work, you have to define the function startsWith as a filter in your angular app.
See this angular documentation
Also your parameter name is state but the typeahead will return the country code of the state so be careful with your variable names.

Strange bug with ng-repeat and filter

I'm using NodeJS, ANgularJS, and MongoDB with mongoose
Here is my model :
var PostSchema = new mongoose.Schema({
nomReseau : String,
corps : String,
etat : String,
section : String
});
I got a function that change the attribute etat:
$scope.passer = function(index){
var post = $scope.posts[index];
post.etat = "enCours";
Posts.update({id: post._id}, post);
$scope.editing[index] = false;
}
I'm using a ng-repeat for show object in my database :
<ul>
<li ng-repeat="post in posts ">
<p>
<a ng-show="!editing[$index]" href="#/{{post._id}}">{{post.corps}}</a>
</p>
<button ng-show="!editing[$index]" ng-click="passer($index)">Passer</button>
</li>
</ul>
I can see all post in my database and when I click on the button this works perfectly the attribute etat change and all is fine.
But when I add a filter in the ng-repeat like this :
<li ng-repeat="post in posts | filter:{ etat:'aTraiter'} ">
The filter works great I have all post with the attribute etat:'aTraiter'
But if I click on my previous button and change the attribute etat nothing change and I try with other functions they all work wihout the filter but when I put it nothing work.
The problem is that $index will change if less data is shown (because you're filtering). you could use directly post variable
ng-click="passer(post)"
and your function should be something like
$scope.passer = function(post){
post.etat = "enCours";
Posts.update({id: post._id}, post);
var index = $scope.posts.findIndex(function(p) { /* comparison to get original index */ }); /* keep in mind findIndex is not supported on IE, you might want to use filter or for loop instead) */
$scope.editing[index] = false;
}
you could handle editing in the post variable directly. So in your passer function you can do this
post.editing = false;
and in your view
ng-show="!post.editing"
this way you won't use $index and you will prevent all issues with being updated by filters
There are bugs in AngularJS v1.4 where in certain situations the ng-repeat breaks. I upgraded to v1.6 and it went away.
Do you have any controllers/services that access $scope.editing? If so, you might be setting the $scope.editing[$index] equal a previous state where it wasn't equal to false. You may also want to consider that you are assuming $scope.editing[$index] is going to be a boolean. if it has any other type such as string or number then it will evaluate to true.
Otherwise none of your results have the attribute etat equal to 'aTraiter' so they aren't showing. Have you verified that any of them actually do have etat equal to 'aTraiter'. You might be changing that value somewhere else. Possibly from the Passer function

Multiple $interpolation symbols in AngularJs

I am rather new to AngularJs, but I have a specific need for a more complex, conditional template using multiple interpolation symbols. I am using the same example as in https://docs.angularjs.org/api/ng/service/$interpolate .
I need something like:
[[ {{greeting}}, {{name}} || Hello, {{name}} || Hello, stranger ]]
This should be interpreted as a multiple conditional template, showing the first fragment if both $scope.greeting and $scope.name are defined, the second one if only $scope.name is defined, and the third one otherwise.
The idea is that within symbols [[ ]] the fragments between a || symbol are interpolated using the standard interpolation symbols with AllOrNothing, proceeding from left to right until the first one succeeds, and making sure that the last one always succeeds.
I know that this can be done with something like
<span ng-if='greeting && name">{{greeting}}{{name}}</span>
<span ng-if='name && !greeting">Hello, {{name}}</span>
<span ng-if='!name">Hello, stranger</span>
but this solution is extremely cumbersome, requires to determine which complex set of boolean expressions makes sure that only one span is shown, and adds spurious spans to the DOM just because you need a place for the ng-if directives.
Thank you for all you can suggest.
You can write your own filter to handle this situation specifically. If you want something a little more reusable, in regards to conditional output, you could make an a kind of ternary filter. Here's one called iif (named as such to prevent eval errors we'd get if we called it just if):
.filter('iif', function() {
// usage: {{ conditionToTest | iif:truevalue:falseValue }}
// example: {{ iAmTrue | iif:'I am true':'I am false' }}
return function(input, trueValue, falseValue) {
return input ? trueValue : falseValue;
};
})
Use it like this in your example:
{{greeting | iif:greeting:'Hello'}}, {{name | iif:name:'stranger'}}
You can certainly specialize it further, if that's too verbose:
.filter('valueOrDefault', function() {
return function(input, defaultValue) {
return input || defaultValue;
};
})
Then your template looks like:
{{ greeting | valueOrDefault:'Hello' }}, {{name | valueOrDefault: 'stranger'}}
And so on.
The interpolator should be able to handle it.
<p>{{ greeting || 'Hello' }}, {{ name || 'Stranger' }}.</p>

How to use ng-repeat for dictionaries in AngularJs?

I know that we can easily use ng-repeat for json objects or arrays like:
<div ng-repeat="user in users"></div>
but how can we use the ng-repeat for dictionaries, for example:
var users = null;
users["182982"] = "{...json-object...}";
users["198784"] = "{...json-object...}";
users["119827"] = "{...json-object...}";
I want to use that with users dictionary:
<div ng-repeat="user in users"></div>
Is it possible?. If yes, how can I do it in AngularJs?
Example for my question:
In C# we define dictionaries like:
Dictionary<key,value> dict = new Dictionary<key,value>();
//and then we can search for values, without knowing the keys
foreach(var val in dict.Values)
{
}
Is there a build-in function that returns the values from a dictionary like in c#?
You can use
<li ng-repeat="(name, age) in items">{{name}}: {{age}}</li>
See ngRepeat documentation. Example: http://jsfiddle.net/WRtqV/1/
I would also like to mention a new functionality of AngularJS ng-repeat, namely, special repeat start and end points. That functionality was added in order to repeat a series of HTML elements instead of just a single parent HTML element.
In order to use repeater start and end points you have to define them by using ng-repeat-start and ng-repeat-end directives respectively.
The ng-repeat-start directive works very similar to ng-repeat directive. The difference is that is will repeat all the HTML elements (including the tag it's defined on) up to the ending HTML tag where ng-repeat-end is placed (including the tag with ng-repeat-end).
Sample code (from a controller):
// ...
$scope.users = {};
$scope.users["182982"] = {name:"John", age: 30};
$scope.users["198784"] = {name:"Antonio", age: 32};
$scope.users["119827"] = {name:"Stephan", age: 18};
// ...
Sample HTML template:
<div ng-repeat-start="(id, user) in users">
==== User details ====
</div>
<div>
<span>{{$index+1}}. </span>
<strong>{{id}} </strong>
<span class="name">{{user.name}} </span>
<span class="age">({{user.age}})</span>
</div>
<div ng-if="!$first">
<img src="/some_image.jpg" alt="some img" title="some img" />
</div>
<div ng-repeat-end>
======================
</div>
Output would look similar to the following (depending on HTML styling):
==== User details ====
1. 119827 Stephan (18)
======================
==== User details ====
2. 182982 John (30)
[sample image goes here]
======================
==== User details ====
3. 198784 Antonio (32)
[sample image goes here]
======================
As you can see, ng-repeat-start repeats all HTML elements (including the element with ng-repeat-start). All ng-repeat special properties (in this case $first and $index) also work as expected.
JavaScript developers tend to refer to the above data-structure as either an object or hash instead of a Dictionary.
Your syntax above is wrong as you are initializing the users object as null. I presume this is a typo, as the code should read:
// Initialize users as a new hash.
var users = {};
users["182982"] = "...";
To retrieve all the values from a hash, you need to iterate over it using a for loop:
function getValues (hash) {
var values = [];
for (var key in hash) {
// Ensure that the `key` is actually a member of the hash and not
// a member of the `prototype`.
// see: http://javascript.crockford.com/code.html#for%20statement
if (hash.hasOwnProperty(key)) {
values.push(key);
}
}
return values;
};
If you plan on doing a lot of work with data-structures in JavaScript then the underscore.js library is definitely worth a look. Underscore comes with a values method which will perform the above task for you:
var values = _.values(users);
I don't use Angular myself, but I'm pretty sure there will be a convenience method build in for iterating over a hash's values (ah, there we go, Artem Andreev provides the answer above :))
In Angular 7, the following simple example would work (assuming dictionary is in a variable called d):
my.component.ts:
keys: string[] = []; // declaration of class member 'keys'
// component code ...
this.keys = Object.keys(d);
my.component.html: (will display list of key:value pairs)
<ul *ngFor="let key of keys">
{{key}}: {{d[key]}}
</ul>

Resources