$ scope变量值在AngularJS中$ http成功回调之外无法访问

时间:2021-06-28 18:51:18

I am just started learning AngularJS.

我刚开始学习AngularJS。

I created a simple app to display content in json file. But however the the data assigned to scope inside the $http, returns undefined outside.

我创建了一个简单的应用程序来显示json文件中的内容。但是,分配给$ http内部范围的数据,返回undefined外部。

var app= angular.module('app',[]); 

app.controller('apCtrl',['$scope','$http',function($scope,$http){

  $http.get('/path/to/data.json').success(function(){

   console.log(data); // returns data --working
   $scope.data=data; // assiged
   console.log($scope.data);  // returns data --working

  });

  console.log($scope.data); // returns 'undefined'  --not working

}]);

Please help me to understand this problem.

请帮我理解这个问题。

Thanks!

谢谢!

1 个解决方案

#1


5  

It's because you are making an asynchronous call. The data is not prepared when you try to call it from outside of success function. Check the documentation.

这是因为你正在进行异步调用。当您尝试从成功函数外部调用数据时,不会准备数据。查看文档。

For example, if you wait for a couple seconds, it'ld show:

例如,如果你等待几秒钟,它会显示:

app.controller('apCtrl',['$scope','$http','$timeout',function($scope, $http, $timeout){

  $http.get('/path/to/data.json').success(function(){

   console.log(data); // returns data --working
   $scope.data=data; // assiged
   console.log($scope.data);  // returns data --working

  });
  $timeout(function(){
    console.log($scope.data);
  }, 2000);

}]);

#1


5  

It's because you are making an asynchronous call. The data is not prepared when you try to call it from outside of success function. Check the documentation.

这是因为你正在进行异步调用。当您尝试从成功函数外部调用数据时,不会准备数据。查看文档。

For example, if you wait for a couple seconds, it'ld show:

例如,如果你等待几秒钟,它会显示:

app.controller('apCtrl',['$scope','$http','$timeout',function($scope, $http, $timeout){

  $http.get('/path/to/data.json').success(function(){

   console.log(data); // returns data --working
   $scope.data=data; // assiged
   console.log($scope.data);  // returns data --working

  });
  $timeout(function(){
    console.log($scope.data);
  }, 2000);

}]);