Jmorvan
Jmorvan

Reputation: 1040

Angular translate extend existing translations

I am trying to have external modules change my $translateProvider.translation on the main module. see this as a "tranlation plugin" for my app.

it seems like changing translations from the $translate service is not possible.

mymodule.service('MyService', function ($translateProvider) {
    var lib = function () {
    //EDITED FOR BREVITY
        this._registerTranslations = function (ctrl) {
            if (!ctrl.i18n) return;
            for (var name in ctrl.i18n) {
            /////////////////////////////
            // THIS IS THE PLACE, OBVIOUSLY PROVIDER IS NOT AVAILABLE!!!!
               $translateProvider.translations(name, ctrl.i18n[name]);
            //////////////////////////////
            }
        };
    //EDITED FOR BREVITY
    };
    return new lib();
});

anyone with a bright idea?

Upvotes: 1

Views: 3135

Answers (3)

Pascal Precht
Pascal Precht

Reputation: 8893

So, to answer your question: there's no way to extend existing translations during runtime with $translate service without using asynchronous loading. I wonder why you want to do that anyway, because adding translations in such a way means that they are already there (otherwise you would obviously use asynchronous loading).

Upvotes: 1

Jerrad
Jerrad

Reputation: 5290

Have a look at the Asynchronous loading page. You can create a factory that will load a translation from wherever you want.

I created an Angular constant to hold new translations. If I want to add a new translation, I add it to the constant. Then in my custom loader, I first check the constant to see if the translation exists (either a new one, or an updated one). If so, I load it from the constant. If not, I load it from a .json file (or wherever you load your initial translations from). Use $translate.refresh() to force translations to be reloaded and reevaluated.

Demo here

The demo is pretty simple. You would need to do a little more work if you wanted to just change a subset of the translations, but you get the general idea.

Upvotes: 1

m.e.conroy
m.e.conroy

Reputation: 3538

From the AngularJS docs (https://docs.angularjs.org/guide/providers):

You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.

Providers are to be used with the application's .config function. $translateProvider for configuration, $translate for other services and controllers.

Upvotes: 0

Related Questions