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

Demo 阅读:44 2025-06-02 22:19:02 评论:0

我正在阅读这篇文章: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(); 
}); 


标签:ajax
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号