htm01
htm01

Reputation: 919

How to get the response data into a global scope array in AngularJS?

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) ?

Upvotes: 2

Views: 3701

Answers (1)

Gloopy
Gloopy

Reputation: 37785

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
});

Upvotes: 3

Related Questions