Closed Nickproger closed 8 years ago
You can extend the behavior of ng-i18next in order to change the language on the back-end before calling reInit
in ng-i18next.
Example code:
.config(['$provide', function($provide) {
// complete $i18next with a setLng method
$provide.decorator('$i18next', ['$delegate', '$http', '$q', '$rootScope',
function($delegate, $http, $q, $rootScope) {
$delegate.setLng = function(lng, cb) {
// call back-end's i18next with the command to change language
return $http.get('/locales/resources.json?setLng=' + lng)
.then(function() {
var def = $q.defer();
// return when reload task has finished
var off = $rootScope.$on('i18nextLanguageChange', function() {
off();
def.resolve();
(cb || function () {})();
});
// re-init $i18next to fetch the new translations
$delegate.reInit();
return def.promise;
})
;
};
return $delegate;
}]);
}])
Now, $i18next.setLng('fr')
returns a promise that it has been done, or you can use a callback style : $i18next.setLng('fr', callback)
.
NB: /locales/resources.json
is the default url to the translations in i18next. You may change it depending on your project.
@efolio , thank you. Actually i fixed it by using filters in all labels, kind of this: {{ 'hello' | i18next:{ {lng: myCurrentLangFromScope} } }}, but looks like it's not the best solution. @archer96, @efolio, could this functionality be included into release? I think it's quite often usecase when we want to change language on page without page reloading..
How to change default language?