1

how to store the $http response in a global $scope variable?

$scope.data = [];
 $http({
     method: 'POST',
     url: '/generateId',
     headers: {
         'Content-Type': 'multipart/form-data'
     },
     data: {
         name: 'userid'
     },
     transformRequest: function(data, headersGetter) {
         var formData = new FormData();
         angular.forEach(data, function(value, key) {
             formData.append(key, value);
         });
         var headers = headersGetter();
         delete headers['Content-Type'];
         return formData;
     }
 }).
 success(function(data, status, headers, config) {
     $scope.data = data;
     console.log('$scope.data in success-->', $scope.data);//data is coming
 }).
 error(function(data, status, headers, config) {
     console.log('id is failed');
 });
 console.log('$scope.data outside-->', $scope.data);//empty array is coming

how to access the response outside the success? Is there any solution?

Thanks.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Siva GV
  • 81
  • 2
  • 13
  • 1
    possible duplicate of [How to return the response from an Ajax call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – raina77ow Dec 08 '14 at 12:20
  • This is different. The question is specifically about angular and not jquery. – orange Dec 08 '14 at 12:28
  • $scope.data should be accessible from in and outside of success. – orange Dec 08 '14 at 21:03

1 Answers1

0

scope.data = $resource(...) will store a promise and the final result (once received) in the variable.

Both scopes are the same object.

The reason why $scope.data is empty for you is because the requests gets executed asynchronously. At the time you log the value outside of the success method, the request hasn't been returned yet. If you want to do something with the data you have to do it in the success method (if you just want to display it, angular should work fine). Try adding a {{ data }} to your html template and see how the data gets populated.

orange
  • 7,755
  • 14
  • 75
  • 139