javascript - Inject service/object into controller after an asynchronous (ajax) call -


i globalizing website developed both asp.net mvc , angularjs. js part using angular-localization load resource bundles.

right have controller this:

app.controller('mycontroller', ['$scope', function($scope) {   $scope.msg = "hello world!"; }]); 

with nglocalize can use locale service, getting resource string in callback:

app.controller('mycontroller', ['$scope', 'locale', function($scope, locale) {   locale.ready('resourcefile').then(function() {     $scope.msg = locale.getstring('resourcefile.helloworld');   }); }]); 

the problem have translate hundreds of strings , introducing callback makes hard review code, , forces me change controller logic (e.g: when need resource string inside function return message caller). call locale.getstring() directly, without callback:

app.controller('mycontroller', ['$scope', 'locale', function($scope, locale) {     $scope.msg = locale.getstring('resourcefile.helloworld'); }]); 

maybe locale.ready() promise called before controller initialized, preloading resource files inside locale service.

please keep in mind dealing legacy code , website not single page application, cannot use routeprovider / resolve (apparently) not option here.

any insights appreciated.

the ideal way solve using resolve feature ng-route or ui-router, views/controllers not instantiated until data resolve available.

you can same thing, albeit in less elegant way:

<div ng-if="dataisavailable>   <div ng-controller="mycontroller"></div> </div> 

in above, mycontroller won't instantiated until expression in ng-if true.

now need pre-load resource files , make data available other application components. simple example:

angular.factory('mylocaleservice', function(locale) {    var  mylocaleservice = function() {};   var localedata = {};    mylocaleservice.prototype.loadresource = function() {     locale.ready('resourcefile').then(function() {       // data resource file , iterate on       // store data in local var... example doing       // simple assignment       localedata['mystring'] = locale.getstring('mystring');     });   }    mylocaleservice.prototype.getstring = function(string) {     return localedata[string];   }    return new mylocaleservice(); }); 

putting together:

when app starts, pre-load url's (mylocaleservice.loadresource()). defer instantiation of views/controllers until data available using ng-if or similar. inject mylocaleservice controllers , use fetch resource bundle strings.


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -