Get current language with angular-translate

﹥>﹥吖頭↗ 提交于 2019-11-28 15:54:30

问题


Is there a way to get the current used language in a controller (without $translateProvider)?

Couldn't find anything in the $translate service.


回答1:


$translate.use() is a getter and setter.

See this demo found in links of docs:

http://jsfiddle.net/PascalPrecht/eUGWJ/7/




回答2:


$translate.use() is the way to go. Also, when an asynchronous loader is executed, you might wanna use $translate.proposedLanguage() which returns the language key of the language that is currently loaded but not finished loaded yet.




回答3:


When using angular-translate-loader-static-files I have noticed that $translate.proposedLanguage() returned undefined when using the default language while $translate.use() always returned the proposed language.

Therefore I fixed it by using:

var currentLang = $translate.proposedLanguage() || $translate.use();



回答4:


$translate.use() seems not to work on initial load of the app, to get last selected language from storage: $translate.storage().get( $translate.storageKey() ) or just $translate.proposedLanguage();




回答5:


The $translate service has a method called preferredLanguage() that return what you want. The return of this function is the string of the language, like 'en'.

Here i wrote you an example:

angular.module('traslateApp').controller('myController', ['$scope', '$translate', function($scope,$translate){
   $scope.changeLanguage = function (langKey) {
      $translate.use(langKey);
   };
   $scope.getCurrentLanguage = function () {
       $translate.preferredLanguage();
   };
}])



回答6:


translate.currentLang is used to check the current selected language in i18n




回答7:


I think this is the better way to determine the language -

$window.navigator.language || $window.navigator.userLanguage



回答8:


Maybe is not related but could be useful. In angular2+ the way to access to the current language is

...
import { TranslateService } from '@ngx-translate/core';

export class MyComponent implements OnInit {
  constructor(private translate: TranslateService) {}

  ngOnInit() {
   translate.use('it');
   const currentLang = this.translate.currentLang;
  }
 }


来源:https://stackoverflow.com/questions/20444578/get-current-language-with-angular-translate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!