AngularJS:将$ http.get数据分配给变量

hwg*_*hwg 3 javascript angularjs angularjs-scope angularjs-controller angularjs-http

我尝试将$ http.get中的数据分配给我的控制器中的变量.

 $http.get(URL).success(function (data) {
      $scope.results = data;
      console.log('results in $http.get :'+ $scope.results);
    });

 console.log('results after http.get'+ $scope.results);
Run Code Online (Sandbox Code Playgroud)

第一个控制台日志打印数据来自get.在$ http.get(url).success $ scope.results打印为undefined之后.

K.T*_*ess 8

这是因为$http.get是异步的.因此,在ajax请求完成之前,您的代码不会被搁置,而是执行其余的代码.所以你的第二个console.log将在ajax请求完成之前执行.此时,没有调用的范围变量$scope.results,仅在请求完成后定义,这就是它打印的原因undefined.您的第一个console.log将仅在$httpajax成功完成后打印,此时您已$scope.results分配data来自后端.