2013-11-29 31 views
0

观看这部影片,AngularJS如何从异步调用返回值?

https://www.youtube.com/watch?v=IRelx4-ISbs

你会发现,代码行写这个:

$scope.twitterResult = $scope.twitter.get({q:$scope.searchTerm}); 

这是一个垃圾的怪癖: “叽叽喳喳的“获得”的方法'显然是一个异步函数,它如何将值返回给$ scope.twitterResult?

的jsfiddle(不能工作的原因Twitter的API已经改变):

http://jsfiddle.net/johnlindquist/qmNvq/

+2

相关:http://stackoverflow.com/q/15464273/497356 –

回答

0

此代码$scope.twitter.get({q:$scope.searchTerm});回报延迟对象。安排角度视图,以便在推迟对象解析时更新视图。这只是一个方便。

+0

但如何延迟对象是否知道应该更改哪个变量?或者延期的对象可以改变自己? – Xieranmaya

+1

当Angular在视图内部遇到诺言时,它会自动设置成功回调,并在解析后将结果值替换为诺言。 在视图上直接使用promise是AngularJS的一个特性,很多人都没有意识到,但它为我们的控制器尽可能地变得精益开辟了很多机会。 例如:http://plnkr.co/edit/pL4lF9JYXZ7EVJNv7PJK?p=preview – iKBAHT

0
$scope.twitterResult = $scope.twitter.get({q:$scope.searchTerm}); 

您的代码仅适用于角度绑定。

但是,如果您需要获取有关运行时间的数据,则需要将此格式写入此格式。

如果$scope.twitter是一个URL,然后把它写

$http.get($scope.twitter, {q:$scope.searchTerm}).success(function (response) { 
$scope.twitterResult=response; 
} 

$ HTTP是位指示定义必须