0

I have an angular controller that is supposed to get products from a database and then perform some operations on them. The controller has a function which has another function inside it. How can I return the data received from the nested function back to the controller? I've tried virtually everything I can think of and nothing seems to be working.

search.controller('SearchResultsController', function($scope, $routeParams, $http){

  $scope.getAllProducts = function(){     //function 1

    var config = {
      method: "GET",
      url: '/products',
      headers: {"Content-Type": "application/json;charset=utf-8"}
    };

  $http(config).then(function(response) {    //function 2
      $scope.allProducts = response.data;
      console.log($scope.allProducts) // correctly prints products fetched from server
    });

$scope.getAllProducts();
console.log($scope.allProducts); //prints undefined

};
};
ninesalt
  • 4,054
  • 5
  • 35
  • 75
  • So you want to call an asynchronous method synchronously? You can't. Work with promises. – Casey May 23 '16 at 14:44
  • you can use $q which run functions asynchronously, and return values (or exceptions) when they are done processing. – fyasir May 23 '16 at 14:49

1 Answers1

0

Your function is most likely working, but it's an asynchronous function call, so it hasn't completed before the next line executes. I would recommend that you consider refactoring this code to use services, but based on how you currently have your code structured anything you need to do at startup of your controller should come within the then function in your call to $http.

Mike Feltman
  • 5,160
  • 1
  • 17
  • 38