Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular-translate - Fallback language for determinePreferredLanguage()

I use angular-translate in my app. How can I register a fallback language if the determinePreferredLanguage() returns a language key my code doesn't know?

I want to fall back to english if someone from e.g. Sweden visits my site (language key: sv). But since I haven't listed sv in my registerAvailableLanguageKeys function, it fails, and the language-keys are shown to the user instead of the translation.

$translateProvider
    .registerAvailableLanguageKeys(['da-dk','en-us'], {
        'en_US': 'en-us',
        'en_UK': 'en-us',
        'da': 'da-dk',
    })
    .determinePreferredLanguage();
like image 602
swenedo Avatar asked Aug 29 '14 10:08

swenedo


3 Answers

Hey I had a similar issue to yours, the way I solved it was :

I added this to my app.config

  $translateProvider.useStaticFilesLoader({
      prefix: 'the/directory/locale-',
      suffix: '.json'
    })

  .registerAvailableLanguageKeys(['en'])

  .determinePreferredLanguage()

  .fallbackLanguage('en');

and this to my app.run:

$rootScope.changeLanguage = function() {
  if(/[a-z]{2}_[A-Z]{2}/.test($translate.use())) {
    $translate.fallbackLanguage($translate.use().split('_')[0]);
  }
}

that way if the browser detects a language such as fr_BE it will try to fall back to fr and then once again en, in your case you would want sv. Also having the registerAvailableLanguageKeys seems to stop the determinePreferredLanguage() causing an error with the non-existant file issue. I hope this helps someone.

like image 36
Ciaran George Avatar answered Dec 07 '22 15:12

Ciaran George


Using wildcards is the best solution, you can just set en_* as follows:

    $translateProvider.useStaticFilesLoader({
       prefix: 'locales/locale-',
       suffix: '.json'
    })   

    .registerAvailableLanguageKeys(['en','fr','pt'], {
       'en_*': 'en',
       'fr_*': 'fr',
       'pt_*': 'pt',
       '*': 'en'
    })

    .determinePreferredLanguage()

    .fallbackLanguage('en');

for files:

locales/locale-en.json
locales/locale-fr.json
locales/locale-pt.json
like image 184
Adriano Spadoni Avatar answered Dec 07 '22 15:12

Adriano Spadoni


You can use $translateProvider.fallbackLanguage(['en-us']) to determine your fallback language, and $translateProvider.preferredLanguage(langKey)to set your preferred language.

Also note that fallbackLanguage() can have an array of languages as a parameter, which means you can have several ordered fallback languages.

like image 28
alcfeoh Avatar answered Dec 07 '22 17:12

alcfeoh