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

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

问题描述

我无法访问 AngularJS 控制器中的数组,但它在视图中有效.

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

在控制器中:.results 返回 undefined

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

在视图中:.results 返回一组推文

In the view: .results returns an array of tweets

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

推荐答案

$resource 调用是异步的,但 $resource 服务在调用时立即为 resource.get 调用返回一个空白对象(或空数组resource.query 调用).然后,只有在 promise 得到解决(服务器返回响应)之后,$resource 服务才会将实际结果分配给 $scope.twitterResult 变量.

$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.

这就是为什么 $scope.twitterResult 在立即访问 (console.log) 时为空白,但(似乎)在您看来有效"的原因.

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

你的视图表达式 {{$scope.twitterResult.results}} 一开始也是 undefined,但是 Angular 的 $parse 服务(负责解析视图表达式)没有输出 undefined 因为它不是设计的.一旦收到服务器响应,视图表达式就会更新,并显示 twitterResult.results.

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.

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

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