AngularJS : get translate key in app.js

Chéramy Alexandre picture Chéramy Alexandre · May 23, 2014 · Viewed 9.8k times · Source

In my application, I use the AngularJS module Pascal Precht (translate module). I come to you because I can not get in my method myApp.Run of app.js a translation key. I can do in a controller or a view. But impossible to get it at the initialization of the project. It shows me the key, not correspondence.

Do you have a solution?

Here is my code:

var myApp = angular.module('myApp', ['ngRoute', 'ngAnimate', 'myApp.filters', 'myApp.services', 'myApp.directives', 'pascalprecht.translate']);

// Declare routeProvider
myApp.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/', {templateUrl:'partials/connectView.html', controller:'ConnectController'});
    $routeProvider.when('/homeView', {templateUrl:'partials/homeView.html', controller:'HomeController'});
}]);

// Declare translateProvider
myApp.config(['$translateProvider', function($translateProvider) {        
    $translateProvider.useStaticFilesLoader({
        prefix: 'res/localization/lang-',
        suffix: '.json'
    });

    $translateProvider.preferredLanguage('fr_FR');
    //$translateProvider.preferredLanguage('en_US');
}]);

// Declare Global variables
myApp.run(['$rootScope', '$filter', function($rootScope, $filter) {
    $rootScope.list = false;
    etc....

    //I'm trying to get translate Key but it doesn't work
    console.log($filter('translate')('MY_KEY'));
}]);

My AngularJS version is 1.2.16 (last stable version). Thx

Answer

Onur Yıldırım picture Onur Yıldırım · Jun 2, 2014

Try injecting the $translate service in app.run().

angular-translate version 1.1.1 and below

myApp.run(['$rootScope', '$translate', '$log', function ($rootScope, $translate, $log) {
    $log.debug($translate('MY_KEY'));
}]);

I'd also suggest you to upgrade to the latest version of Pascal Precht's angular-translate. There are some changes in the new version.

angular-translate version 2.0.0 and above

myApp.run(['$rootScope', '$translate', '$log', function ($rootScope, $translate, $log) {
    // translate via promises (recommended way)
    $translate(['MY_KEY', 'MY_OTHER_KEY'])
            .then(function (translation) {
                $log.debug(translation.MY_KEY);
            });
    // translate instantly from the internal state of loaded translation
    $log.debug($translate.instant('MY_KEY'));
}]);

See this helpful migration guide.