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

htm01
  • 849
  • 1
  • 7
  • 19

1 Answers1

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
});
Gloopy
  • 37,767
  • 15
  • 103
  • 71
  • 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... – htm01 Jan 28 '13 at 04:20
  • 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](http://docs.angularjs.org/api/ng.$rootScope.Scope) – Gloopy Jan 28 '13 at 04:27
  • 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](http://stackoverflow.com/a/12506203/1207991). – Gloopy Jan 28 '13 at 04:32