Search code examples
angularjsangular-translate

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?


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