如何访问AngularJS控制器通过$资源GET填充的数组()? [英] How to access an array in AngularJS controller populated by $resource get()?

查看:194
本文介绍了如何访问AngularJS控制器通过$资源GET填充的数组()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法访问数组中的AngularJS控制器,但它在视图中工作。

在控制器:。结果返回undefined

 函数TwitterCtrl($范围,$资源){  $ scope.twitter = $资源('http://search.twitter.com/:action',
      {行动:search.json',问:angularjs',回调:JSON_CALLBACK},
      {得到:{方法:JSONP',则params:{RPP:4}}});    $ scope.twitterResult = $ scope.twitter.get({Q:榜样});    //返回资源对象
    的console.log($ scope.twitterResult)    //返回undefined
    的console.log($ scope.twitterResult.results);
}

在该视图:。结果返回鸣叫数组

  //此方法返回的鸣叫数组
{{$ scope.twitterResult.results}}


解决方案

$资源调用是异步的,但是$资源服务返回一个空对象 resource.get 立即调用在调用(或空数组 resource.query 电话)。然后,只有在承诺得到解决(服务器返回响应),在$资源服务分配实际结果的 $ scope.twitterResult 变量。

这就是为什么 $ scope.twitterResult 是直接访问(执行console.log)空白,但是(貌似)在您的视图作品。

您认为前pression {{$ scope.twitterResult.results}} 也未定义在第一,但角度的解析$服务(负责分析视图前pressions)不输出未定义,因为它的设计都不到。当服务器收到响应,认为前pression被更新,而 twitterResult.results 显示。

I can not access an array in the AngularJS controller but it works in the view.

In the controller: .results returns undefined

function TwitterCtrl($scope, $resource){

  $scope.twitter = $resource('http://search.twitter.com/:action',
      {action:'search.json', q:'angularjs', callback:'JSON_CALLBACK'},
      {get:{method:'JSONP', params: {rpp: 4}}});

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

    //returns the resource object
    console.log($scope.twitterResult)

    //returns undefined
    console.log($scope.twitterResult.results);
}

In the view: .results returns an array of tweets

//This returns an array of tweets
{{$scope.twitterResult.results}}

解决方案

$resource calls are asynchronous, but $resource service returns a blank object for resource.get calls immediately on invocation (or empty array on resource.query calls). Then, only after the promise gets resolved (server returns response), the $resource service assigns the actual results to the $scope.twitterResult variable.

That's why $scope.twitterResult is blank on immediate access (console.log), but (seemingly) 'works' in your view.

Your view expression {{$scope.twitterResult.results}} is also undefined at first, but Angular's $parse service (responsible for parsing view expressions) does not output undefined because it's designed not to. As soon as server response is received, the view expression is updated, and twitterResult.results are displayed.

这篇关于如何访问AngularJS控制器通过$资源GET填充的数组()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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