Dru*_*Dru 0 javascript angularjs angular-ui angularjs-scope
我无法访问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);
}
Run Code Online (Sandbox Code Playgroud)
在视图中:.results
返回一组推文
//This returns an array of tweets
{{$scope.twitterResult.results}}
Run Code Online (Sandbox Code Playgroud)
$ resource调用是异步的,但$ resource服务在resource.get
调用时立即返回一个空白对象(或调用时为空数组resource.query
).然后,只有在promise得到解决后(服务器返回响应),$ resource服务才会将实际结果分配给$scope.twitterResult
变量.
这就是为什么$scope.twitterResult
立即访问(console.log)是空白的,但(看似)在你的视图中"有效".
您的视图表达式{{$scope.twitterResult.results}}
最初也是未定义的,但Angular的$ parse服务(负责解析视图表达式)不会输出,undefined
因为它的设计不是.收到服务器响应后,视图表达式将立即更新并twitterResult.results
显示.
归档时间: |
|
查看次数: |
5010 次 |
最近记录: |