AngularJS : Setting languages in angular-translate from Controller or Service

Joel Basson picture Joel Basson · Sep 11, 2014 · Viewed 36.3k times · Source

I am interested in using angular-translate.

Due to a lot of setup calls that happen initially on startup, I cannot provide the language json during config. Nor is it possible to use the async loader. I need to be able to specify the languages from a controller or service at a later point.

$translateProvider.translations(.., ...) is the call to use, but $translateProvider isn't available in controllers or services, but seemingly only at config.

$translate doesn't seem to have the ability to load a language JSON.

Is there any workaround?

Answer

Mikko Viitala picture Mikko Viitala · Sep 11, 2014

First inject $translate into your controller.

app.controller('MainCtrl', function($scope, $state, $translate) {});

Then you can get and set current language with $translate.use().

var lang = $translate.use(); // holds current lang
$translate.use(lang);  // sets lang to use

 

If you need to add new translations after config, then you can use partial loaders.

// config example
app.config(function($translateProvider, $translatePartialLoaderProvider){
  // "known" translations here, in {lang}.main.json, if any
  $translatePartialLoaderProvider.addPart('main'); 
  $translateProvider.useLoader('$translatePartialLoader', {
    urlTemplate: '/path/to/files/{lang}.{part}.json'
  });
});

// controller
app.controller('MainCtrl', function($scope, $translate, $translatePartialLoader){
  $translatePartialLoader.addPart('translation');
  $translate.refresh();
  $translate.use('en');
});

// en.translation.json
{ "KEY" : "Value", ... }

 

If that is not dynamic enough, then you can always do the translation on-the-fly.

// config
app.config(function($translateProvider, $translatePartialLoaderProvider){
    $translateProvider.preferredLanguage('en');
    $translateProvider.translations('en',{
      'TITLE': '{{ title }}',
      'SUBTITLE': '{{ subtitle }}',
      'STATIC': 'This is static'
    });
});

// controller
app.controller('MainCtrl', function($scope, $translate){
  $scope.dynamic = {
    'title': 'This is my header',
    'subtitle': 'My subtitle'
  };
});

// template
<pre>{{ 'TITLE' | translate:dynamic }}</pre>
<pre>{{ 'SUBTITLE' | translate:dynamic }}</pre>
<pre>{{ 'STATIC' | translate }}</pre>

This would spit out something like

enter image description here