2

I want to get the data of an http response permanently into a scope array to access it globally in my controller :

function myCtrl($scope, $http){    
$scope.data = [];
$http.get('myurl').success(function(data, status) {

       $scope.data = data;
        });
console.log($scope.data)// the output is an empty array, it didn't change
...
}

what am I doing wrong here ? how can I extract the data of the response to a scope array (for example : $scope.data) ?

1 Answer 1

3

The $http.get request/response hasn't completed yet by the time you are doing console.log. You should put the console.log inside your success callback like this:

$http.get('myurl').success(function(data, status) {
    $scope.data = data;
    console.log($scope.data); // the output should be set
});
Sign up to request clarification or add additional context in comments.

3 Comments

I'm not interested in the console.log(), it's there just for demonstrating. As my question says what I want is to get the data of the response into the $scope.data and access it beyond the success function...
Your code should work as is as long as the data being returned in the success function is what you are expecting. Doing $scope.data = data; should set the scope's data variable to the result and be accessible within that controller's scope after the callback executes. If you wanted it to be accessible in other controllers take a look at $rootScope
Also note if you are trying to bind to $scope.data in your UI you may have some issues when setting it to a new array in the success callback since the originally bound array will have been replaced. You can try emptying the array and pushing the contents to the existing array if this is the problem as described in this post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.