1

I'm trying to use Jed for translating an angular app. For this, I use an Angular service providing the Jed object. Now, Jed already needs the translations, which are stored in a JSON file, when it is created:

jed = new Jed( jsonData );
alert( jed.gettext( 'I am translated!' ) );

So, with an Ajax request,

app.factory( 'jed', function ( $http ) {

    var ret = { jed: null };

    $http.get( 'i18n/de_CH/messages.json' )
            .success( function ( data ) {
                ret.jed = new Jed( data );
            } );

    return {
        get jed() {
            // Is null until we receive messages.json
            return ret.jed;
        }
    };
} );

Problem is that jed is not initialised until the HTTP request returns.

Possible solution is to return a deferred object, but then usage is ugly as we always have to check the deferred object and use function callbacks, and also inlined {{jed.gettext( 'Quit' )}} does not work anymore.

Is there a clean way of doing this?

2
  • I just noticed there is angular-jed and checking it – still interested in the programmatic solution tough. Commented Jul 8, 2015 at 12:42
  • 1
    One solution would be to embed the json object in your index.html. Saves you an http call, too. Commented Jul 8, 2015 at 12:59

1 Answer 1

1

Yes, there is a way.

Make it

return {
    get jed()
        return ret;
    }
};

and watch for the changes in the object.

Here's a demo from my another answer that shows the approach.

Another option is to always return promises from async services:

app.factory( 'jed', function ($http) {
    return $http.get( 'i18n/de_CH/messages.json')
} );

And and unwrap them in controller:

jed.then(function (data) {
    $scope.jed = new Jed(data);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Would $watch still work with inlined calls in templates, i.e. the {{ jed.gettext('translate me') }}? Since then I would have to be be watching the result of function calls. What would it look like when returning promises, does every single controller have to wait for it to resolve?
Sure, bindings and $watch will work for function as well, as soon as it will appear on the scope ($http should trigger another digest cycle). Just make sure the function is efficient enough for that, cache it if it is not.
Added an example for promises, it does the similar job, it is a matter of taste which pattern is better, I prefer to not pollute the controller with promises from services. No, controllers won't wait, provide loading indicators for them. Take a look at ngRoute/uiRouter controllers instead if you really need application-wide resolves.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.