Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 344
Joel Basson Avatar asked Sep 11 '14 08:09

Joel Basson


People also ask

What is translate in AngularJS?

Internationalization Libraries for AngularJS angular-translate is an AngularJS module that provides filters and directives, along with the ability to load i18n data asynchronously. It supports pluralization through MessageFormat , and is designed to be highly extensible and configurable.

How does i18n work in AngularJS?

AngularJS supports i18n/l10n for date, number and currency filters. Localizable pluralization is supported via the ngPluralize directive. Additionally, you can use MessageFormat extensions to $interpolate for localizable pluralization and gender support in all interpolations via the ngMessageFormat module.

Does AngularJS support Internationlization?

AngularJS supports inbuilt internationalization for three types of filters currency, date and numbers. We only need to incorporate corresponding js according to locale of the country. By default it handles the locale of the browser.


2 Answers

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

like image 95
Mikko Viitala Avatar answered Oct 05 '22 23:10

Mikko Viitala


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;
        }
    }
});
like image 30
Joel Basson Avatar answered Oct 05 '22 23:10

Joel Basson