1

Ok, so I have a service with a function that does an HTTP request and the value returned is set to $scope, however this does not work because it seems $scope is not waiting for the AJAX call. How would I go about returning an AJAX result from a service function outside the controller?

Example:

//Controller
app.controller('Controller', function($scope, $http, Service){

    // $scope WILL NOT BE SET TO THE VALUE RETURNED, the returned value is UNDEFINED
    $scope = Service.getData();

}


// Get server data from service function
app.service('Service', function ($http){

    this.getData = function(){
        //Get server data

       return { data: result }
    }
}
Vivek Pratap Singh
  • 9,326
  • 5
  • 21
  • 34
user3704920
  • 617
  • 1
  • 8
  • 19

3 Answers3

0

Try putting the service call in the resolve function and inject the result into your controller.

This blog post has a great example: http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx

link
  • 2,480
  • 1
  • 16
  • 18
0

You can not wait for ajax call. That's why "A" in AJAx stands for asynchronous. You can try syncrhonous call(which should be avoided) or try callback function to set your scope.

For example,

//service
this.getData=function(callback){
callback({data:result});
}

//controller
Service.getData(function(response){
$scope = response;
})
sean
  • 1,644
  • 1
  • 15
  • 14
0

You will need to run a callback function once the Ajax call has finished. So it would look something like this.

//Controller
app.controller('Controller', function($scope, $http, Service){

   // $scope WILL NOT BE SET TO THE VALUE RETURNED, the returned value is UNDEFINED
   Service.getData(function(data) {
      $scope = data;
   });

}


// Get server data from service function
app.service('Service', function ($http){

   this.getData = function(callback){
       //Get server data
      callback({data: result});
   }
}
Roq Savage
  • 142
  • 1
  • 3
  • 7