【发布时间】:2017-12-03 04:18:25
【问题描述】:
我正在尝试在 POST 请求中使用 AngularJS,但我无法在事件中使用 $scope。
这是我的代码(出于演示目的,我只是在 Angular 构造中添加状态):
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)!
}
};
}
通过代码中的 cmets 添加,回调一直有效,直到 EventHandler 分配。
我正在寻找的是:如何使用回调(或更准确地说如何使$scope 在事件处理函数中可用/传输)?
【问题讨论】:
-
使用
$http发出请求。您正在尝试在角度上下文之外的异步代码中修改范围。当您这样做时,需要告诉 angular 运行摘要以更新视图。使用$http在内部处理这个问题 -
欲了解更多信息,请参阅AngularJS $http Service API Reference。
标签: javascript angularjs angularjs-scope angularjs-http