Search code examples
javascriptangularjsangular-translate

Force translation into certain language with angular-translate


I have two translations for my app, English and German, but I need my invoicing module to use a separate language setting.

Is there a way to force the labels on the invoicing page to use the language I set in the invoice_language variable?

So instead of

{{ 'TD_ID' | translate }}

I need something like

{{ 'TD_ID' | translate:'{"language": invoice_language}' }}

Solution

  • Bind your TD_ID only once in your controller swapping the language before you do so.

    In your view, instead of:

    {{ 'TD_ID' | translate }}
    

    simply bind without translate filter:

    {{ 'TD_ID' }}
    

    and in your controller:

    function setInvoiceTranslations(key){
      var invoice_language = 'de';
      currentLang = $translate.use();
      $translate.use(invoice_language);
      var translateText;
      $translate(key).then(function (translatedtext) {
        $scope[key] = translatedtext;
        $translate.use(currentLang);
      });
    
    }
    
    setInvoiceTranslations('TD_ID');
    

    To see this in action see this plunker (which adapts the "How it works" example from angular-translate.github.io).

    See this page on angular-translate's docs for information about this technique (please read "Things to keep in mind" on that page).

    (make sure you inject $translate into your controller, or where-ever you end up putting the setInvoiceTranslations() function)