是什么使得Angular.js一个AJAX调用的最佳做法是什么? [英] What is the best practice for making an AJAX call in Angular.js?

查看:107
本文介绍了是什么使得Angular.js一个AJAX调用的最佳做法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读这篇文章:<一href=\"http://eviltrout.com/2013/06/15/ember-vs-angular.html\">http://eviltrout.com/2013/06/15/ember-vs-angular.html

和它说,

由于它的缺乏的约定,我不知道有多少角项目
  依靠陋习,如AJAX直接控制器中调用?
  由于依赖注入,开发商注射路由器
  参数代入指令?都是新手AngularJS开发商要
  组织他们code的方式,一个有经验的开发人员AngularJS
  认为是地道?

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控制器调用。为什么是不好的做法?什么是制作 $ HTTP 调用那么最好的做法是什么?为什么?

I am actually making $http calls from my Angular.js controller. Why is it a bad practice? What is the best practice for making $http calls then? and why?

推荐答案

编辑:这答案主要集中在版本1.0.X.以prevent混乱它被改变以反映的角所有当前版本为最佳答案今天,2013年12月5日。

我们的想法是创建一个返回承诺返回的数据服务,然后调用,在你的控制和处理的承诺也来填充你的$ 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;
                        });
        }
   }
});

控制器:

办理承诺的则()方法和获取数据出来。设置$ 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;
    });
});

在-查看无极分辨率(仅1.0.X):

在角1.0.X,原来这里的答案的目标,承诺将获得由视图特殊处理。当他们解决,他们的解析值将被绑定到视图。 这一直是德$ P $在1.2.X pcated

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();
});

这篇关于是什么使得Angular.js一个AJAX调用的最佳做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆