我无法访问AngularJS控制器中的数组,但它在视图中工作。
在控制器中:.results
返回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
返回推文数组
//This returns an array of tweets
{{$scope.twitterResult.results}}
答案 0 :(得分:5)
$ resource调用是异步的,但是$ resource服务在调用时立即返回resource.get
调用的空白对象(或resource.query
调用上的空数组)。然后,只有在promise得到解决后(服务器返回响应),$ resource服务才会将实际结果分配给$scope.twitterResult
变量。
这就是为什么$scope.twitterResult
在立即访问(console.log)时是空白的,但(貌似)在您的视图中“有效”。
您的视图表达式{{$scope.twitterResult.results}}
一开始也是未定义的,但Angular的$ parse服务(负责解析视图表达式)不会输出undefined
,因为它的设计并非如此。收到服务器响应后,视图表达式将立即更新,并显示twitterResult.results
。