Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
As the other answers have pointed out the method is asynchronous so it returns immediately. The success callback is called when it does finish and populates your variable, and if you have set your bindings up correctly your UI will update. It's behaving exactly as it should. –  Lee Willis Dec 3 '14 at 9:03
    
Now i try to get data like this : var getSomething = function(){ return $http({method:"GET", url:URL}).then(function(result){ return result.data; }); }; and assign result to variable : $scope.results = getSomething(); –  hwg Dec 3 '14 at 9:13

2 Answers 2

up vote 5 down vote accepted

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.

share|improve this answer
    
@ktoress so how does one get http.get to not be asynchronous and get the value in scope? –  Demodave Feb 12 at 14:57
    
The value will go to $scope anyway, but can take longer (let's say half a second). The point is when or where do you want to use it. If you want to show it on the view, you might use an event to assure it's loaded or just wait. If you need it for another function, you could call that function inside the sucess() call. –  Puce Mar 10 at 11:55

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.