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
可用/傳輸的事件處理函數)?
使用'$ http'發出請求。您正嘗試修改角度上下文外部的異步代碼中的作用域。當你這樣做的角度需要被告知運行一個摘要來更新視圖。使用'$ http'可以在內部處理 – charlietfl
有關更多信息,請參閱[AngularJS $ http服務API參考](https://docs.angularjs.org/api/ng/service/$http)。 – georgeawg