I'm facing a major issue in my AngularJS application. I have a factory module with an getAll() function that retrieves JSON data from the server. In the controller module, I attempt to assign the value returned by the factory's getAll() function to scope.eventSports.
The problem is that the variable assignment happens before the getAll() function returns with the data. So, initially, the variable is undefined and then gets populated with the result of getAll() function.
How can I make sure the variable assignment waits for the completion of the getAll() function?
The factory:
var gameDataFactory = angular.module('gameDataFactory', []);
gameDataFactory.factory('gameDataFactory', ['gameService', function(gameService) {
var sportEvents = {
getAll : function(){
gameService.getGroupedEvents()
.success(function(data) {
console.log(data.sportEvents);
return data.sportEvents;
})
.error(function(error) {
return null;
});
}
};
return {
sportEvents: sportEvents
};
}]);
The controller:
gameControllers.controller('SportEventListCtrl', ['$scope', 'gameService', 'gameDataFactory', '$sce',
function($scope, gameService, gameDataFactory, $sce) {
$scope.sportEvents = {};
$scope.status = true;
$scope.sportEvents = gameDataFactory.sportEvents.getAll();
console.log($scope.sportEvents);