Reputation: 12129
I am using this
instead of $scope
for an angular app, which is leading to difficulties when I try and access the the result of the get
request in my controller.
My factory looks like this:
app.factory('footballService', function($http) {
return{
getAllTeams : function() {
return $http({
url: 'url',
dataType: 'json'
})
}
}
});
and my controller looks like this:
app.controller('footballController', function(footballService) {
var footballController = this;
footballService.getAllTeams().success(function(data){
console.log(data); //this data is shown
footballController.teams = data;
});
console.log(footballController.teams); //this is undefined
});
The issue is that I want to access the teams outside getAllTeams()
. Can anyone explain how can I access this variable? I thought by setting var footballController = this;
would allow me to access this throughout the controller, but I must be misunderstading how it Angular works.
Thanks for any help in advance.
Upvotes: 0
Views: 59
Reputation: 6813
Move your console call into the success
callback.
app.controller('footballController', function(footballService) {
var footballController = this;
footballService.getAllTeams().success(function(data){
console.log(data); //this data is shown
footballController.teams = data;
console.log(footballController.teams); //this is populated now
});
});
Upvotes: 0
Reputation: 339796
Your getAllTeams()
function is returning a "promise" - the underlying data is not available until the asynchronous call has completed.
You can therefore only safely access that data within a .then
callback (AFAIK .success
is deprecated), but it needn't be the same callback as the one in which you assigned the data to the current scope:
var promise = footballService.getAllTeams().success(function(data){
console.log(data); //this data is shown
footballController.teams = data;
});
promise.then(function() {
console.log(footballController.teams);
});
Upvotes: 1