Search code examples
javascriptangularjsangular-translate

Get the selected language when using $translate


I've setup the $translate project from here in my angularjs app.

In my app.config() I've set the default language to the $translateProvider but how to get the selected language in the langCtrl? Does $translate have a get function for this?

angular.module('app').config(['$translateProvider', function($translateProvider) {
  $translateProvider.useStaticFilesLoader({
      prefix: 'locale-',
      suffix: '.json'
  });
  $translateProvider.preferredLanguage('en');
}]);

angular.module('app').controller('langCtrl', ['$scope', '$translate',
    function ($scope, $translate) {

        $scope.lang = ''; //here I need to set the selected language

        $scope.setLanguage = function (langKey) {
            $translate.use(langKey);
        };
}]);

Solution

  • From the official doc we can tell that with $translate.use() we can determine the current used language.

    (...)

    use([key])

    If no or a falsy key is given it returns the currently used language key. The returned string will be undefined if setting up $translate hasn't finished.