I'm building an angular app. A sort of template to start future projects faster. It's an open source project so you can find the whole project here : https://github.com/maxime1992/webTemplate
I'm using ui-router and angular-translate. I wanted users to be able to share url with current language in it. As you can see here, in the default redirection of ui-router i'm using a default language variable which as to be set first :
// define default language code
var default_lang = 'fr';
// default redirection
$urlRouterProvider.otherwise('/'+default_lang+'/home');
So far, so good. Now i would like to detect user's language. I found out this in angular-translate doc.
But in my angular config, if i ask the library to set language automatically and get the new language, it returns undefined.
$translateProvider.determinePreferredLanguage();
console.log($translateProvider.use()); // return undefined
I can detect it in my controller with :
console.log($translate.proposedLanguage()); // return 'en'
BUT it is too late. I need to detect it in config. Otherwhise, i don't know where to redirect user if lang argument is not in url ...
Do you have any idea ? I really need to find a solution as fast as possible for my work. If i wasn't clear, just tell me and i'll add/edit my question.
Thanks !
答案 0 :(得分:2)
用法如下。
在配置阶段
// call to try to find out browser locale
$translateProvider.determinePreferredLanguage();
配置阶段后
// If determinePreferredLanguage was successful preferredLanguage
// will return the browser locale. Eg 'en_EN'
// Otherwise it will return empty string.
var preferredLanguage = $translate.preferredLanguage(); // returns browser locale
之后,您可以导航到您想要的网址,例如:
$state.go('home', {lang: preferredLanguage});