2017-12-02 5 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が定義されているためです。

「ネイティブ」の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 
     }); 
    } 
} 
関連する問題