2017-12-02 82 views
0

我試圖在POST請求中使用AngularJS,但在事件中我不能使用$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'發出請求。您正嘗試修改角度上下文外部的異步代碼中的作用域。當你這樣做的角度需要被告知運行一個摘要來更新視圖。使用'$ http'可以在內部處理 – charlietfl

+1

有關更多信息,請參閱[AngularJS $ http服務API參考](https://docs.angularjs.org/api/ng/service/$http)。 – georgeawg

回答

1

您不需要將$scope轉換爲callback,原因$scope定義在控制器範圍內。

您在使用「原生」Ajax時可能會遇到問題,導致此操作在Angular之外並且角度不知道,因此您需要熟悉Angular與$scope.$apply

如果您需要製作快捷方式,Angular會爲您提供$http服務。

您可以更換整個XMLHttpRequest與注射$ http和調用.post方法:

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 
     }); 
    } 
}