Reputation: 65
I try to assign data from $http.get to variable in my controller.
$http.get(URL).success(function (data) {
$scope.results = data;
console.log('results in $http.get :'+ $scope.results);
});
console.log('results after http.get'+ $scope.results);
First console log print data from get. After $http.get(url).success $scope.results prints as undefined.
Upvotes: 3
Views: 7446
Reputation: 21901
This is because $http.get
is asynchronous. So your code is not put on hold until ajax request is complete, instead it will execute the rest of the code. So your second console.log
will be executed before the ajax request completes. At this point there is no scope variable called $scope.results
, which is defined only after the request completes, that's why it prints undefined
. Your first console.log
will print only after $http
ajax completes with success, at this point you have $scope.results
which is assigned to data
coming from backend.
Upvotes: 8
Reputation: 20033
$http
is an asynchronous
function. It returns instantly however it returns a promise
not a real result. When the request is completed onsuccess
is called.
The second (the one outside the call) console.log
executes before $http
returns.
Upvotes: 2