Search code examples
angularjsangular-ui-routerangular-translate

How can I make angular translate work with ui-router?


I need to make my old angular 1.5.6 application localized. I use ui-router. And it doesn't work. I am trying to find the reason why, but it seems that others have questions about further steps, while I'm stuck on the first one...

Here is the simplified code of my app:

angular
    .module('localeApp', [
      'ngCookies',
      'ui.router',
      'pascalprecht.translate'
    ])
    .config(
      ['$stateProvider','$urlRouterProvider', '$translateProvider',
      function($stateProvider,$urlRouterProvider, $translateProvider) {
        $urlRouterProvider.otherwise('/login');
        $stateProvider
          .state('login', {
            url: '/login',
            templateUrl: 'loginTpl.html'
          })
          .state('welcome', {
            url: '/welcome',
            templateUrl: 'welcomeTpl.html'
          })
          .state('other', {
            url: '/other',
            templateUrl: 'otherTpl.html'
          });

        $translateProvider.useMissingTranslationHandlerLog();// log missing translations
        $translateProvider.useStaticFilesLoader({
            prefix: 'locale-',// path to translations files
            suffix: '.json'// suffix, currently- extension of the translations
        });
        $translateProvider.preferredLanguage('en_US');// is applied on first load
        $translateProvider.useLocalStorage();// saves selected language to localStorage


    }])
    .run(['$rootScope', '$translate', function($rootScope, $translate) {
      $rootScope.$on('$stateChangeSuccess',
            function(event, toState, toParams, fromState, fromParams){
                $translate.refresh();
            });
    }]);

There are json files defined for each locale. For example the default locale-en_US.json:

{
  "translate.welcome": "welcome",
  "translate.login": "login",
  "translate.other": "other"
}

And the template loginTpl.html page:

<p>This is {{translate.login | translate}} page</p>

Everything is in this plunker.

I can see that the json file is retrieved, but it is not applied. I'm sure that I'm missing something obvious, but I just can't figure out what it is...


Solution

  • Wrap translate pattern with ' a.e.:

    Instead:

    <p>This is {{translate.login | translate}} page</p>
    

    write:

    <p>This is {{'translate.login' | translate}} page</p>
    

    Demo