0

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()
}]);
1
  • 1
    show suggestions is sync, while airports http callback is async. Other than that there's not problem accessing scope variables from functions. Commented Apr 8, 2016 at 20:53

1 Answer 1

3

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);
    }
}]);
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, seriously, I made same mistake with async and sync thing again. I think, this time it's a last time, lesion learned.

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.