且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Angular.js 中进行 AJAX 调用的***实践是什么?

更新时间:2023-09-08 10:43:28

此答案主要针对 1.0.X 版.为了防止混淆,它已被更改以反映截至今天(2013 年 12 月 5 日)所有当前版本的 Angular 的***答案.

我们的想法是创建一个服务,该服务返回对返回数据的承诺,然后在您的控制器中调用它并处理那里的承诺以填充您的 $scope 属性.

The idea is to create a service that returns a promise to the returned data, then call that in your controller and handle the promise there to populate your $scope property.

module.factory('myService', function($http) {
   return {
        getFoos: function() {
             //return the promise directly.
             return $http.get('/foos')
                       .then(function(result) {
                            //resolve the promise as the data
                            return result.data;
                        });
        }
   }
});

控制器:

处理 promise 的 then() 方法并从中获取数据.设置 $scope 属性,然后执行您可能需要执行的任何其他操作.

The Controller:

Handle the promise's then() method and get the data out of it. Set the $scope property, and do whatever else you might need to do.

module.controller('MyCtrl', function($scope, myService) {
    myService.getFoos().then(function(foos) {
        $scope.foos = foos;
    });
});

In-View Promise 解决方案(仅限 1.0.X):

在 Angular 1.0.X 中,这里是原始答案的目标,promise 将得到 View 的特殊处理.当它们解析时,它们解析的值将绑定到视图.此功能已在 1.2.X 中弃用

module.controller('MyCtrl', function($scope, myService) {
    // now you can just call it and stick it in a $scope property.
    // it will update the view when it resolves.
    $scope.foos = myService.getFoos();
});