从$ scope.function访问$ scope.variable

时间:2016-04-08 20:50:03

标签: angularjs

在此代码中,我的console.log会记录undefined。我试图从其他$ scope方法访问$ scope属性。如何正确地做到这一点?

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 个答案:

答案 0 :(得分:3)

您的代码尝试在发送 http请求后立即记录$scope.departureLocations的值,以便从后端获取它们。目前,http响应尚未恢复,$scope.departureLocations = data;行尚未执行。

AJAX中的第一个A意味着异步

在传递给$scope.showSuggestions()的函数内移动success()。而顺便说一下,使用then()代替success()success()已被弃用。

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