i18next / ng-i18next

translation for AngularJS using i18next
https://github.com/i18next/ng-i18next
MIT License
161 stars 54 forks source link

Is there a way to change current language to another with dynamic reloading of all labels on the page? #63

Closed Nickproger closed 8 years ago

Nickproger commented 10 years ago

How to change default language?

efolio commented 10 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.

Nickproger commented 9 years ago

@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..