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('/: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}}
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./: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}}
Share
Improve this question
edited Mar 18, 2013 at 13:57
Mark Rajcok
365k114 gold badges500 silver badges494 bronze badges
asked Mar 17, 2013 at 18:06
DruDru
9,83014 gold badges51 silver badges68 bronze badges
3
- See also stackoverflow./questions/14373661/angularjs-data-assignment – Mark Rajcok Commented Mar 18, 2013 at 13:59
-
Thanks mark. That post describes what I've been trying to achieve. I put all of my code in the
success
callback in order to use theresults
array. I wish I could assign the array to a variable and access it outside of that function. – Dru Commented Mar 18, 2013 at 16:02 -
You can do that -- e.g., $scope.twitterResult = $scope.twitter.get(...)` -- as long as you also add a
$watch('twitterResult', function(newValue) { ... })
to detect when it gets asynchronously updated. – Mark Rajcok Commented Mar 18, 2013 at 16:10
1 Answer
Reset to default 5$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.