Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: assign $http.get data to variable

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.

like image 909
hwg Avatar asked Sep 09 '26 06:09

hwg


1 Answers

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.

like image 103
Kalhan.Toress Avatar answered Sep 11 '26 20:09

Kalhan.Toress



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!