0

How can I access the $scope or the data obtained from success in $http outside the $http.jsonp() request?

$http.jsonp('http://example.com/?callback=JSON_CALLBACK')
    .success(function(data) {
        $scope.info1 = data.name;
        $scope.info2 = data.company;
    });

console.log("access it here outside: ",$scope.info1);

currently the console prints undefined.

Thanks for the help.

0

1 Answer 1

1

You shouldn't consider asynchronous ajax call to be work in synchronous way. You have to wait until that ajax/promise gets finished. Though don't use .success/.error they are deprecated, use .then instead to chain promise.

You must rely on the promise to promise gets resolve/reject.

Code

var promise = $http.jsonp('http://example.com/?callback=JSON_CALLBACK')
promise.then(function(response) {
    var data = response.data;
    $scope.info1 = data.name;
    $scope.info2 = data.company;
    console.log("access it here outside: ",$scope.info1);
    myOtherFunction($scope.info1);
})
.catch(function(error) {
    console.log(error);
});
Sign up to request clarification or add additional context in comments.

7 Comments

what should i use instead of success? could please provide the alternative way? thanks
it still doesn't get printed! i get undefined.
your console log is still INSIDE the then, i mean completely outside the code related to the thenand $http, i want to use it in another function in the same controller.
You ahve to call that other dependant function from .then of current jsonp call
could you please give an example?
|

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.