Force translation into certain language with angul

2019-07-13 07:51发布

问题:

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}' }}

回答1:

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)



回答2:

You can create your custom filter (ex. "wordKey" | translateTo: languageKey ) and call the $translate service:

.filter('translateTo', function ($translate) {
  return function (key, lang) {
   return $translate.instant(key, {}, undefined, lang);
  }; });

You can force the word to be translated on the fly without modifying the global language.

https://angular-translate.github.io/docs/#/api/pascalprecht.translate.$translate



回答3:

Let follow this doc: https://angular-translate.github.io/docs/#/api/pascalprecht.translate.$translate You can translate a text to a specific language with forceLanguage param; For example:

$translate('PUSH_NOTIFICATION.NEW_RATING', {}, undefined, undefined, 'ar').then(function (translatedText) {
     if(translatedText){
         ..do something
 });  

//'PUSH_NOTIFICATION.NEW_RATING' is Translate KEY in your language file
// {}  for dynamic values
// 'ar' a specific language


回答4:

Another way to do this is using angular-translate's built in translate-language directive as so:

<div translate-language="{{ invoice_language }}">
    {{ 'TD_ID' | translate }}
</div>

No need to create a custom one or do anything in the controller.

https://angular-translate.github.io/docs/#/api/pascalprecht.translate.directive:translateLanguage