2016-10-14 4 views
0

티켓 관리 테이블을 만들고 있는데, 아약스 함수 밖에서 변수를 내보내려고 할 때 몇 가지 문제가 있습니다.각도 아약스, 함수 외부에 정의되지 않은 변수

내 코드 : 서버가 응답 할 때 공장

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 

같은 결과 나는 .then에서 실행 어떤 어떤 변수

+0

모든 논리를 콜백 약속 콜백. – reptilicus

+0

[비동기 호출의 응답을 어떻게 반환합니까?] (http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) 가능한 중복 –

+0

GET은 console.log에서 계속 진행됩니다. 왜냐하면 함수가 비동기 적이기 때문에 실행되고 코드가 계속 될 수 있기 때문입니다. GET이 코드를 반환하면 그 부분에서 코드가 시작되고 절대 종료되지 않습니다. 그래서 console.log는 결코 다시는 발생하지 않습니다. 이미 좋은 대답이 있습니다. – jedi

답변

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은 아직 정의되지 않은 이유를 이제 볼 수행이 같은 프로그램에 대해 생각해? 코드의 위치는 중요하지 않습니다. 중요한 것은 실행되는 시간이 인 것입니다.. 새로 수정 된 $scope.ticketModify을 사용하여 더 많은 작업을 수행하려면 thenthen에 연결해야합니다. 또는 다른 함수를 호출하고 현재 then에서 $scope.ticketModify을 전달하십시오. 너는 무엇이든 할 수있어! tickets.php에 대한 호출이 반환 된 후

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 
 
    }

당신을 위해 확실히 노력하고있는 곳이다.

작동하지 않는 곳은 액세스하는 시간에 ticketModify가 정의되어 있지 않기 때문입니다. ticket.php를 비동기 호출로 호출하고 약속이 해결 된 후 채워지는 변수에 즉시 액세스하려고했습니다.

그래서, 당신이 할 수있는 모든 tickets.php과 성공에 대한 값을 업데이트하는 HTTP 호출하기 전에 범위에 ticketModify을 선언하는 것입니다/다음 tickets.php에에 있어야 할 무엇의

관련 문제