AngularJS: assign $ http.get variables to a variable
I am trying to assign data from a $ http.get variable to a 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);
The first console log prints data from get. After $ http.get (url) .success, $ scope.results prints as undefined.
source to share
This is because it $http.get
is asynchronous. This way your code won't hold until the ajax request is made, instead it will execute the rest of the code. This way your second console.log
will be executed before the ajax request completes. At the moment, there is no scope variable $scope.results
that is only determined after the request completes, so it prints undefined
. Your first one console.log
will only be printed after the $http
ajax execution completes successfully, at the moment you have the $scope.results
assigned data
one coming from the backend.
source to share