Angular Ajax,函数外部的未定义变量

时间:2016-10-14 20:38:29

标签: javascript angularjs ajax

我正在构建一个票证管理表,我在尝试将一个变量导出到ajax函数之外时遇到了一些问题。

我的代码:

app.controller('bodyController',function($scope,$http,$sce){
$scope.ticketList = [];
$http.get("tickets.php")
.then(function(response) {
   $scope.ticketModify = response.data;
    console.log($scope.ticketModify); //this one return the correct data.
    return $scope.ticketModify;
});
console.log($scope.ticketModify); //this return undefine

如果我尝试将response.data返回到任何变量

,则与工厂的结果相同

3 个答案:

答案 0 :(得分:1)

仅仅因为代码在物理上高于其他代码并不意味着它从上到下执行。想想你的程序:

app.controller('bodyController',function($scope,$http,$sce){
$scope.ticketList = [];
$http.get("tickets.php")
   .then(handleResponse);
console.log($scope.ticketModify); //this return undefine

function handleResponse(response) {
    $scope.ticketModify = response.data;
    console.log($scope.ticketModify); //this one return the correct data.
    return $scope.ticketModify;
}

你现在看到为什么$scope.ticketModify仍未定义?代码的位置无关紧要,重要的是执行时间。如果您想对新修改的then进行更多操作,则应将另一个then链接到您在那里的$scope.ticketModify。或者,调用其他函数并从当前$scope.ticketModify传递then。你可以做任何事情!

答案 1 :(得分:0)

服务器响应时执行.then中执行的操作。 但是在'$ http.get'Promise之后,下一个代码将被执行。

你应该研究异步编程和Promises。 https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise

答案 2 :(得分:0)



app.controller('bodyController', function($scope, $http, $sce) {
      $scope.ticketList = [];
      $scope.ticketModify = "";
      $http.get("tickets.php")
        .then(function(response) {
          $scope.ticketModify = response.data;
          console.log($scope.ticketModify);
          return $scope.ticketModify;
        });
      console.log($scope.ticketModify);
      // This  should print a empty String
    }




它正好适合你的地方,是在返回ticket.php的调用之后。

它无法正常工作的地方是因为您访问时未定义ticketModify。您将tickets.php称为异步调用,并立即尝试访问在解析承诺后正在填充的变量。

因此,您所能做的就是在http调用tickets.php之前在范围内声明ticketModify,并在ticket.php上更新成功/然后回调的值