Sergio Morstabilini
Sergio Morstabilini

Reputation: 2055

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?

Upvotes: 3

Views: 5024

Answers (2)

StefanR
StefanR

Reputation: 31

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.

Upvotes: 3

frank
frank

Reputation: 156

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

Upvotes: 2

Related Questions