gpt4 book ai didi

javascript - 如何访问 AngularJS Controller 中由 $resource get() 填充的数组?

转载 作者:行者123 更新时间:2023-11-28 13:44:24 24 4
gpt4 key购买 nike

我无法访问 AngularJS Controller 中的数组,但它可以在 View 中使用。

在 Controller 中:.results 返回未定义

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

在 View 中:.results 返回推文数组

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

最佳答案

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

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

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

关于javascript - 如何访问 AngularJS Controller 中由 $resource get() 填充的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15464273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com