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

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


Got there in the end.

in the .config

$translateProvider.useLoader('customLoader');

the customLoader...

angular.module('myapp').factory('customLoader', function ($q, TranslationService) {

    return function (options) {
        var deferred = $q.defer();

          deferred.resolve(TranslationService.getLanguages().filter(function(lang){
                return lang.key == options.key
          })[0].values);

        return deferred.promise;
    };

});

and then a TranslationService to share the data

angular.module('myapp').factory('TranslationService', function () {
    var languages = [];

    return {
        setLanguages: function (data) {
            languages = data;
        },

        getLanguages: function () {
            return languages;
        }
    }
});

Maybe check this:

http://www.ng-newsletter.com/posts/angular-translate.html

Under "Switching the language at runtime"

$translate.use(); // Returns the currently used language key
$translate.use('en'); // Sets the active language to `en`

app.controller('TranslateController', function($translate, $scope) {
  $scope.changeLanguage = function (langKey) {
    $translate.use(langKey);
  };
});