Javascript 如何使用AngularJS执行XMLHttpRequest(AJAX)

Javascript 如何使用AngularJS执行XMLHttpRequest(AJAX),javascript,angularjs,angularjs-scope,angularjs-http,Javascript,Angularjs,Angularjs Scope,Angularjs Http,我试图在POST请求中使用AngularJS,但无法在事件中使用$scope 这是我的代码(出于演示目的,我只是在Angular构造中添加状态): 正如通过代码中的注释添加的那样,回调一直工作到EventHandler分配 我要寻找的是:如何使用回调(或者更准确地说,如何使$scope在事件处理程序函数中可用/传输)?您不需要将$scope传递到回调中,因为$scope是在控制器范围内定义的 您在使用“本机”Ajax时可能会遇到问题,因为此操作不属于Angular,Angular不知道,您需要熟

我试图在POST请求中使用
AngularJS
,但无法在事件中使用
$scope

这是我的代码(出于演示目的,我只是在Angular构造中添加状态):

正如通过代码中的注释添加的那样,回调一直工作到EventHandler分配


我要寻找的是:如何使用回调(或者更准确地说,如何使
$scope
在事件处理程序函数中可用/传输)?

您不需要将
$scope
传递到
回调中,因为
$scope
是在控制器范围内定义的

您在使用“本机”Ajax时可能会遇到问题,因为此操作不属于Angular,Angular不知道,您需要熟悉Angular

如果你需要做一个快捷方式,Angular会通过服务为你做

您可以将整个
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
        });
    }
}

使用
$http
发出请求。您正在尝试修改异步代码中超出角度上下文的范围。执行此操作时,需要告知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
        });
    }
}