2017-12-02 12 views
0

AngularJS을 POST 요청 내에서 사용하려고하지만 이벤트 내에서 $scope을 사용할 수 없습니다.AngularJS를 사용하여 XMLHttpRequest (AJAX)를 수행하는 방법

내 코드 그게 전부 (데모 목적을 위해 난 그냥 각도 구조 내에서 상태를 추가) :

코드에 주석을 통해 추가로
myApp.controller('myController', function myController($scope) { 
    $scope.myVal = [{status:"before (working)"}]; 

    doRequest(p1, p2, myCallback.bind(null, $scope)); 

    function myCallback($scope, a) { 
     $scope.myVal = [{ status: a }]; 
    } 

    function doRequest(p1, p2, callback) { 
     $scope.myVal = [{ status: "prepare request (working)" }]; 

     var xhr = new XMLHttpRequest(); 
     var url = "http://..."; 
     xhr.open("POST", url, true); 
     //.... 
     xhr.send(myQuery); 

     $scope.myVal = [{ status: "after post send (working)" }]; 
     callback("after post via callback (working)"); 

     //callback working till this point 

     xhr.onreadystatechange = function() { 

      if (xhr.readyState === 4 && xhr.status === 200) { 
       callback("in event (NOT working)"); 
       //This is NOT working anymore (even this point is reached)! 
      } 
     }; 
    } 

, 콜백은 이벤트 핸들러 할당까지 노력하고 있습니다.

내가 찾고있는 것 : 콜백 (또는 더 정확한 방법을 $scope 사용할 수 있도록/이벤트 처리기 함수에서 전송 된) 사용하는 방법?

+2

사용'$ http' :

당신은 .post 방법을 $ HTTP를 주입 호출하여 전체 XMLHttpRequest을 대체 할 수 있습니다. 각도 컨텍스트 외부의 비동기 코드에서 범위를 수정하려고합니다. 그렇게하면 각도를 업데이트하여 다이제스트를 실행하여보기를 업데이트해야합니다. '$ http'를 사용하여 내부적으로 처리합니다. – charlietfl

+1

자세한 내용은 [AngularJS $ http 서비스 API 참조] (https://docs.angularjs.org/api/ng/service/$http)를 참조하십시오. – georgeawg

답변

1

$scopecallback에 전달할 필요가 없으므로 $scope이 컨트롤러 범위 내에 정의되어 있습니다.

"native"Ajax를 사용할 때 문제가 발생할 수 있습니다.이 작업은 Angular의 범위를 벗어나 각도가 알 수 없기 때문에 각도에 익숙해 져야합니다 ($scope.$apply).

바로 가기를 작성해야하는 경우 Angular는 $http 서비스로 해결해 드렸습니다. 요청을 할

myApp.controller('myController', function myController($scope, $http) { 
    $scope.myVal = [{status:"before (working)"}]; 

    doRequest(p1, p2); 

    function doRequest(p1, p2) { 
     $scope.myVal = [{ status: "prepare request (working)" }]; 
     $http.post(url, myQuery).then(() => { 
      $scope.myVal = [{ status: 'Finished' }]; // $scope is available here 
     }); 
    } 
}