How to access an array in AngularJS controller pop

2019-09-02 15:26发布

问题:

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

回答1:

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