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