angularjs - Load JSON in angular service -
i'm trying use jed translating angular app. this, use angular service providing jed object. now, jed needs translations, stored in json file, when created:
jed = new jed( jsondata ); alert( jed.gettext( 'i translated!' ) ); so, 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 { jed() { // null until receive messages.json return ret.jed; } }; } ); problem jed not initialised until http request returns.
possible solution return deferred object, usage ugly have check deferred object , use function callbacks, , inlined {{jed.gettext( 'quit' )}} not work anymore.
is there clean way of doing this?
yes, there way.
make it
return { jed() return ret; } }; and watch changes in object.
here's a demo answer shows approach.
another option return promises async services:
app.factory( 'jed', function ($http) { return $http.get( 'i18n/de_ch/messages.json') } ); and , unwrap them in controller:
jed.then(function (data) { $scope.jed = new jed(data); });
Comments
Post a Comment