angularjs - 在 Angular.js 中进行 AJAX 调用的最佳实践是什么?

标签 angularjs

我正在阅读这篇文章:http://eviltrout.com/2013/06/15/ember-vs-angular.html

它说,

Due to it’s lack of conventions, I wonder how many Angular projects rely on bad practices such as AJAX calls directly within controllers? Due to dependency injection, are developers injecting router parameters into directives? Are novice AngularJS developers going to structure their code in a way that an experienced AngularJS developer believes is idiomatic?



我实际上正在制作$http来自我的 Angular.js Controller 的调用。为什么这是一个不好的做法?制作$http 的最佳做法是什么?那么电话呢?为什么?

最佳答案

编辑:这个答案主要关注版本 1.0.X。为防止混淆,它已被更改以反射(reflect)截至今天 2013 年 12 月 5 日所有当前版本的 Angular 的最佳答案。
这个想法是创建一个服务,该服务向返回的数据返回一个 promise ,然后在您的 Controller 中调用它并在那里处理 promise 以填充您的 $scope 属性。
服务

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;
                        });
        }
   }
});
Controller :
处理 promise 的then()方法并从中获取数据。设置 $scope 属性,然后做任何你可能需要做的事情。
module.controller('MyCtrl', function($scope, myService) {
    myService.getFoos().then(function(foos) {
        $scope.foos = foos;
    });
});
In-View Promise Resolution(仅限 1.0.X):
在 Angular 1.0.X 中,这里原始答案的目标, promise 将得到 View 的特殊处理。当它们解析时,它们的解析值将绑定(bind)到 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();
});

关于angularjs - 在 Angular.js 中进行 AJAX 调用的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17646034/

相关文章:

html - 如何重叠 ng-repeat 列表中的元素 - 位置 : absolute?

angularjs - 如何从指令部分调用 ng-click?

html - 如何从 Angular 中绑定(bind)的字符串中删除双引号?

javascript - 动态更新 CSS

angularjs - 使用 Visual Studio Code 批量删除 AngularJS 项目中未使用的导入

angularjs - 如何在 if 条件下调用 state.go 时阻止 Controller 的执行?

angularjs - Angular 自定义过滤器不显示

javascript - Firefox:iframe 中的 AngularJS 应用程序抛出 nsresult: "0x80004005 (NS_ERROR_FAILURE)"错误

javascript - 未知提供者 : $stateProviderProvider <- $stateProvider

angularjs - $sce.trustAsHtml 不起作用