angularjsajaxhttpscopestoring-data

How to store http angularjs call response to variable


I'm making http get call from angularJS function. Call works perfectly and get the response back but I need to store response in a variable so I can use it outside of $http. I tried to keep in $scope.data.submissionFileID but alert($scope.data.submissionFileID) says undefined. Also I want me make this call synchronous. I'm new to this, can you please help to modify this below code?

     $scope.openWindow = function (e) {
        
        var url = '/Submission/GetSubmissionFileInfo?' + 'id=' + SubmissionID;
        $http.get(url).success(function (response) {
        $scope.data.submissionFileID = response; // response is an integer such as 123
        }); 
        alert($scope.data.submissionFileID); // This is undefined, what should I do to fix it?
        
        var content = "<h7><b>" + "Created at  </b>" + $scope.data.submissionFileID + "</h7><br><br>";
        
    }

Solution

  • Something to consider is that the alert(...) is being called before the async function has a chance to complete. An option would be to send the response off to another function that sets the $scope variable and does whatever else you might want.

    $scope.openWindow = function (e) {
    var url = '/Submission/GetSubmissionFileInfo?' + 'id=' + SubmissionID;
       $http.get(url).success(function (response) {
          $scope.doTheThing(response);
       }); 
    }
    
    $scope.data = {}
    
    $scope.doTheThing = function(response) {
       $scope.data.submissionFileID = response;
    }
    

    in the HTML template file...

    <div ng-if="!data.submissionFileID">Retrieving Data....</div>
    <div ng-if="data.submissionFileID">
    <h7><b>Created at </b> {{data.submissionFileID}}</h7>
    </div>