Reputation: 47
I have a big problem in my angular js application. I have a factory module which has a getAll() function, this get the json data from the server. And I have the controller module where I try to assign the factory's getAll() function's value to the scope.eventSports.
My problem is that, the variable assign is run first, and it does not wait that the getAll() function return back with the data. The variable assign run at first with the undefinied... and then I get the result of getAll() function.
How can I achieve the variable assign wait 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) {
// Get the json data from the server.
// This gives back the data, but later, this run at second time...
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;
// I should somehow assign this scope variable with callback
$scope.sportEvents = gameDataFactory.sportEvents.getAll();
// This run first and this is undefinied.
console.log($scope.sportEvents);
Upvotes: 1
Views: 995
Reputation: 3823
There are several ways of implementing this functionality, such as returning the deferred object. Another simpler approach is to pass $scope to getAll function, and bind whatever data to the passed $scope.
Upvotes: 0
Reputation: 92
Change this line
gameService.getGroupedEvents()
to
return gameService.getGroupedEvents()
Upvotes: 1