无法在ajax调用中设置Angular范围变量

Cod*_*ess 0 ajax scope angularjs

var req = {
            "RequestId": $scope.$parent.req_id,
            "RequestDate": new Date(),
            "RequestDetails": $scope.$parent.details
        };

$scope.req_result = "test";

$.ajax({
            type: "POST",
            url: 'http://localhost:49358/api/myClasses/PostRequest',
            data: JSON.stringify(req),
            contentType: "application/json;charset=utf-8",
            processData: true,
            success: function (data, status, xhr) {
                console.log("The result is : " + status);
                $scope.req_result = "Post succeeded";
            },
            error: function (xhr) {
                $scope.req_result = "ERROR: " + xhr.responseText
            }
        });
Run Code Online (Sandbox Code Playgroud)

范围变量$ scope.req_result未设置,因此当我尝试在html视图页面上显示它时:

<span>{{req_result}}</span>
Run Code Online (Sandbox Code Playgroud)

它显示默认值.不知何故ajax正在做什么是不知道角度

Pra*_*ant 6

$scope.$apply()在从非角度上下文修改范围变量后,您忘记通过调用来启动摘要循环.

success: function (data, status, xhr) {
    $scope.req_result = "Post succeeded";
    $scope.$apply();
},
error: function (xhr) {
    $scope.req_result = "ERROR: " + xhr.responseText
    $scope.$apply();
}
Run Code Online (Sandbox Code Playgroud)

Angular通过创建一个名为" 观察者 "的东西来更新神奇的视图.当你这样做时{{ someScopeVariable }},Angular正在为该范围变量创建观察者.就像你通过编程以编程方式创建一个观察者一样

$scope.$watch('someScopeVariable', function myListenerFunction() {
    // When someScopeVariable changes, do this
});
Run Code Online (Sandbox Code Playgroud)

观察者与称为消化周期的东西齐头并进.从Angular中的不同位置,例如$ timeout回调或$ http.then()回调等,Angular从$ rootScope调用摘要周期.这基本上是遍历范围内的所有观察者,如果观察的值已经改变,则调用上面的myListenerFunction之类的监听器函数.

重要的是Angular在内部触发了这个摘要周期.所以,当你使用jQuery中的$ .ajax()时,你会错过这个.您可以更改正在监视的范围变量

{{req_result}}

但是,没有观察者知道它.$scope.$apply()通过从根范围启动摘要循环,确保所有观察者都知道此更改.

更好的解决方案是使用Angular的内部$ http服务,该服务可用于发出XHR请求,当调用回调函数时,Angular会自动触发摘要周期.

var req = {
            "RequestId": $scope.$parent.req_id,
            "RequestDate": new Date(),
            "RequestDetails": $scope.$parent.details
        };

$scope.req_result = "test";

$http
    .post('http://localhost:49358/api/myClasses/PostRequest', req)
    .then(
        function () {
            $scope.req_result = "Post succeeded";
        }, 
        function () {
            $scope.req_result = "ERROR";
        }
    );
Run Code Online (Sandbox Code Playgroud)