0
votes

My application is on angularJs. I new to angular-translate. Gone through few examples like http://angular-translate.github.io/. Every scenario I need to define both the language text (Eg: if i need to change "Title" to English to German i need to define title in two languages $translateProvider.translations('en') $translateProvider.translations('de') ) Is this the only way to translate angularJs application?Is there any way that I can pass text as key and translate according to language selected with out defining both text?

Tried in this way but not worked.

$rootScope.$on('$translateChangeSuccess', function () {
    $translateProvider.preferredLanguage('fa');
    $scope.pageTitle = $translate.instant('Title');
  });

In View:

{{pageTitle}}

Can i know better way to change the text.

1
You mean to say you dont wana define the text values in both the languages?Saima Haji
@SaimaHaji yes i will pass english text as key and need to be translate to required language. Can it be possible?Ajay.k
No You can't. angular-translate expects that if you wana use English and German then for all the text which you are using on you web page, you should provide the values for that in both the languages.Saima Haji
@SaimaHaji Is there any other library?can change text. I need a clarification like if I am providing both the text and values what is the necessary of translate library ?directly i can call the required object and on button click and change the text right?Ajay.k
You need to provide text for all the languages you're supporting. If you dont provide the text for german and change browser language to german, on UI you will see this string literal like this -- {{ pageTitle }} which will look more like a bug to end users.Sagar Agrawal

1 Answers

0
votes

No, this is not allowed. You need to specify the text for all the languages you're supporting. As you rightly shared the url of angular-translate documentation - http://angular-translate.github.io/. You need to make sure all the key and text present for one language is also present for other languages you're supporting. Else it may lead to bugs on UI with string literals showing up like {{ title }} which is not good.

I would also recommend you to define your fallback language by specifying fallbackLanguage and preferredLanguage.

If you have some enum like values coming from the backend, and those are not translated on the backend, I'd recommend you add keys for those enums in your translations and use it at runtime (like I shared above).

You can also use the data entered by the user and concat with localised text like below:

//Let's say $scope.name is the name of the user.
$translate.instant('welcome_msg', [$scope.name]);

//String literal in your translation will have {0} and name will be populated at
//this place at runtime.
'welcome_msg' : 'Welcome {0}'