angularjsangular-translate

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?


Solution

  • 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;
            }
        }
    });