I am developing an angularjs app as a part of my angularjs learning. I have controllers and from there I am calling service layers.
leagueManager.service(&quo
Yeah you will need to use a promise interface. So instead of returning a teams object, directly you'll have to return a promise:
Promise Resources:
In the service:
leagueManager.service("teamsService", function($http){
var deferred = $q.defer();
$http.get('data/teams.json').then(function(data) {
deferred.resolve(data);
});
this.getTeams = function(){
return deferred.promise;
};
});
Then in the controller:
$scope.team = {};
var promise = teamsService.getTeams();
promise.then(function(data) {
$scope.teams = data;
});
This should work fine:
myApp.factory('mainFactory',['$http',function($http){
var mainFactory = {};
mainFactory.getRandomUser = function(){
var promise;
if(!promise){
promise = $http.get('http://api.randomuser.me/').success(function(d){
return d;
});
return promise;
}
};
mainFactory.getRandomImage = function(){
var promise;
if(!promise){
promise = $http.get('http://lorempixel.com/400/200/').success(function(d){
return d;
});
return promise;
}
};
return mainFactory;
}]);