In this code my console.log logs undefined. I am trying to access $scope property from other $scope method. How to do this properly?
AppControllers.controller('DepartureLocationCtrl', [
'$scope','$http',
function($scope,$http){
$http.get('/airports').success(function(data){
$scope.departureLocations = data;
});
$scope.showSuggestions = function(){
console.log($scope.departureLocations);
}
$scope.showSuggestions()
}]);
-
1show suggestions is sync, while airports http callback is async. Other than that there's not problem accessing scope variables from functions.haimlit– haimlit2016年04月08日 20:53:28 +00:00Commented Apr 8, 2016 at 20:53
1 Answer 1
Your code tries to log the value of $scope.departureLocations immediately after you have sent the http request to get them from the backend. At this time, the http response has not come back yet, and the $scope.departureLocations = data; line has not been executed yet.
The first A in AJAX means Asynchronous.
Move $scope.showSuggestions() inside the function passed to success(). And BTW, use then() instead of success(): success() is deprecated.
AppControllers.controller('DepartureLocationCtrl', [
'$scope','$http',
function($scope,$http){
$http.get('/airports').then(function(response){
$scope.departureLocations = response.data;
$scope.showSuggestions()
});
$scope.showSuggestions = function(){
console.log($scope.departureLocations);
}
}]);