如何将 return 从 AJAX 调用绑定到 Angular $scope 变量

How to bind a return from an AJAX call to an Angular $scope variable

我正在构建一个带有 Angular 前端的 ASP.NET MVC 应用程序。 I. 在页面加载时成功调用 Angular GetData() 函数,我已经跟踪以确认 Home/DataRefresh 正在以正确的格式返回数据。

然而,当我使用数据填充视图中的 table 时,没有显示任何内容,没有错误,调用全部完成,table 只是空的。

我怀疑这与您必须如何在非 angular 函数中访问 Angular $scope 有关,但我对 [=28= 太陌生了]js 肯定知道。我已经通读了所有我能找到的文档,但都无济于事。

编辑:根据建议,这里是 $http 调用及其包含的 Angular。

app.controller("processModel", function ($scope) {
    $scope.sortType = 'SchedWk';
    $scope.sortReverse = false;

    $scope.GetData = function() {
        $scope.LoadData();
    };

    $scope.LoadData = function() {
        //$.ajax({
        //    type: "GET",
        //    url: 'Home/DataRefresh',
        //    dataType: "json",
        //    success: function (data) {
        //      $scope.data = data;
        //    }, 
        //    error: function (a, b, c) {
        //        alert("The jqXHR object:  " + a + " Error Type:  " + b + " Error Description:  " + c);
        //    }
        //});
        $http({
            method: "GET",
            url: '/Home/DataRefresh'
        }).then(function success(data) {
            $scope.data = data;
        }, function error(errResponse) {
            alert("y u break it tho");
        });
    };  
});

您可能需要在仅设置数据范围后在处理程序中调用 $scope.apply(),因为 ajax 调用之后的处理程序发生在 Angular 之外。如果您使用 Angular 的 $http 服务而不是 $.ajax,则不需要手动处理。

您在 AJAX 调用中丢失了对 $scope 的引用,因为它嵌套在多个 JavaScript 函数中。使用 JQuery AJAX 调用时,您可以通过调用 $scope.$apply() 强制 AngularJS 获取它,这将再次 运行 摘要循环。

您真的应该使用 $http 或 $q 来利用 JavaScript 中的 Promises。它们非常强大,简化了 JavaScript.

中异步操作的使用

这个 link 应该能让你快速起床 运行:

https://docs.angularjs.org/api/ng/service/$http

要在控制器中包含 $http,您需要按照我的示例注入它。

var app = angular.module('app', []);

app.controller('postController', ['$scope', '$http', function($scope, $http){
    $scope.data = 'empty';
    $scope.runAJAX = function(){
  $http.get('https://jsonplaceholder.typicode.com/posts').then(function(response){
            $scope.data = response.data;
        }).catch(function(error){
            console.log(error);
        });
    }
}]);
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body ng-controller="postController">
    <div>
        {{data}}
    </div>
    <div>
        <input type="button" value="run AJAX" ng-click="runAJAX()"/>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
    <script src="script.js"></script>
</body>
</html>

您需要先注入$http服务:

app.controller("processModel", function($scope, $http) { 
    $scope.sortType = 'SchedWk'; 
    $scope.sortReverse = false; 
    $scope.GetData = function() { 
        $scope.LoadData(); 
    }; 
    $scope.LoadData = function() { 
       $http({ 
            method: "GET", 
            url: '/HomeDataRefresh' 
       }).then(function success(data) { 
            $scope.data = data; 
       }, function error(errResponse) { 
            alert("y u break it tho");
       }); 
    };
});

与 jQuery AJAX 不同,$http 服务 returns 一个 response 对象,其中 data 作为 属性 附加该对象的:

$http({
    method: "GET",
    url: '/Home/DataRefresh'
}).then(function success( ̶d̶a̶t̶a̶ response) {
    ̶$̶s̶c̶o̶p̶e̶.̶d̶a̶t̶a̶ ̶=̶ ̶d̶a̶t̶a̶;̶
    $scope.data = response.data;
}, function error(errResponse) {
    alert("y u break it tho");
});

来自文档:

$http Returns

A Promise that will be resolved (request success) or rejected (request failure) with a response object.

The response object has these properties:

  • data{string|Object} – The response body transformed with the transform functions.
  • status{number} – HTTP status code of the response.
  • headers{function([headerName])} – Header getter function.
  • config{Object} – The configuration object that was used to generate the request.
  • statusText{string} – HTTP status text of the response.
  • xhrStatus{string} – Status of the XMLHttpRequest (complete, error, timeout or abort).

-— AngularJS $http Service API Reference - Returns.