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.
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.