我正在读这篇文章:
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?
我实际上是从我的Angular.js控制器进行$ http调用。为什么这是一个坏的做法?那么,最好的做法是使用$ http调用呢?为什么?
编辑:这个答案主要集中在版本1.0.X.为了防止混乱,它被改变以反映当今版本的Angular的最佳答案,截至今天,2013-12-05。
想法是创建一个服务,返回一个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; }); } } });
控制器:
处理promise的then()方法并从中获取数据。设置$ scope属性,并做任何你可能需要做的事情。
module.controller('MyCtrl',function($scope,myService) { myService.getFoos().then(function(foos) { $scope.foos = foos; }); });
视图内容承诺分辨率(仅限1.0.X):
在Angular 1.0.X中,这个原始答案的目标,promise会得到View的特殊处理。当它们解析时,它们的解析值将绑定到视图。这在1.2.X中已被弃用
module.controller('MyCtrl',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(); });