javascript - In AngularJS, how do I automatically update a value fetched via ajax? -


i want make function fetches info ajax url. e.g in service, have following method:

this.getfavcolor = function(id) {     return $http.get('/colors/get/' + id); } 

and in controller, following:

$scope.favcolor = userservice.getfavcolor( id ); 

the problem is, $scope.favcolor assigned promise in case, , way change value returned ajax, set .success() callback on promise , use update value.

however, becoming cumbersome if have lot of things have fetched via ajax. there shortcut, such may doing this?

this.getfavcolor = function(id, variabletochange) {     return $http.get('/colors/get/' + id).success(function(jsonresult)        {          variabletochange = jsonresult.favcolor;        }); } 

and doing following in controller:

userservice.getfavcolor( id, $scope.favcolor ); 

will method work?

note: i've considered $resource cannot set rest api ajax, please don't suggest it.

the way $resource returning empty object immediatly , adding data object once response arrives server. that's why $resource can return objects or arrays, not primitives.

ng-bind (and shorthand {{ }}) resolves promises though, might better solution. i've created plnkr 3 different examples: http://plnkr.co/edit/woru5emomsgk4wuischu?p=preview

// data.json: {"color":"blue"}  app.service('userservice',function($http, $q){   return {      // return value can accessed {{value.data.color}}     getfavcolor: function(id){       return $http.get('data.json');     },      // return value can accessed {{value}}     getfavcolorwithq: function(id){       var def = $q.defer();       $http.get('data.json').success(function(data){         def.resolve(data.color);       });       return def.promise;     }      // return value can accessed {{value.color}}     ,resourceexample: function(id){       var response = {};       $http.get('data.json').success(function(data){         response.color = data.color;       });       return response;     }   } }); 

Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -