Search code examples
angularjsangularjs-scopengrouteangular-translate

How to introduce constants (Angular-Translate) in angular roots


I have just implemented async translations on my site using this guide;

https://scotch.io/tutorials/internationalization-of-angularjs-applications

They use this code to load the preferred language upon page load;

.constant('LOCALES', {
    'locales': {
      'en_EN': 'English',
      'fr_FR': 'Français'
    },
    'preferredLocale': 'fr_FR'
  })

I was wondering if it would be possible to do this in a route, which would then enable me to fix links to send out to people. So;

 .when('/en', {
        templateUrl: 'views/static/home.html',
        needConnection: false,
        .constant ('LOCALES', {
          'prefferedLocale': 'en_EN'
        }),
      })

Thanks


Solution

  • I suggest you to have a value as long with the constant, the value having the prefferedLocale. Then you register in the $rootScope to listen to $routeChangeStart, and check the new route, if it starts with en/ you use the en_EN prefferedLocale in you value and use the value to translate.

    Additionally, if you positively need the constant, it can be a function that returns the object with the prefferedLocale configured within the routeChange.