0

I have an angular app where two languages are used. I used $translate.instant('id'); in my controller to bind some variables. But when I change the translation language using $translate.use('jp'); The controller variables wont change.

I used 'translate' filter in my HTML. That one will change but controller variables wont change. Is there any way to implement it?

Initialized using the below code.

$translateProvider.useStaticFilesLoader({
  prefix: '/translations/',
  suffix: '.json'
});
$translateProvider.preferredLanguage('en');
$translateProvider.fallbackLanguage('en');
$translateProvider
  .useSanitizeValueStrategy('escape');

In a controller I used the below code. vm.userName = $translate.instant('USER_NAME');

When the language change using the below code

$translate.use('jp');

The username doesn't change.

ucMedia
  • 4,105
  • 4
  • 38
  • 46
Nithin.P
  • 132
  • 9

1 Answers1

0

This happens when your language file is not fully loaded by the time you are calling $translate.instant('USER_NAME')

It is also not recommended to do the translations on your controller because a translation is just a representation (view) and it should not be dealt in your controller logic.

If you simply want to translate the userName you can do this (assuming you have already done it):

<p>{{USER_NAME | translate}}</p>

A closer look at this problem is mentioned in the following SO question:

Correct use for angular-translate in controllers

Check @PascalPrecht (the author of angular-translate) @RobinvanBaalen's answers

Sahan Serasinghe
  • 1,591
  • 20
  • 33