Answer the question
In order to leave comments, you need to log in
Requesting data in a multi-controller factory?
There is a simple data sharing between controllers
.factory('Games', function () {
var games = {
list: []
}
return {
get: getGames,
set: setGames,
};
function getGames() {
return games;
}
function setGames(gamesList) {
games.list = gamesList;
}
})
.controller('MyCtrl1', function($scope,Games){
$scope.games = Games.get()
});
.controller('MyCtrl2', function($scope,Games){
$scope.games = Games.get()
});
и так далее
.controller('MyCtrl1', function($scope,Games,$http){
$scope.games = Games.get()
// если нету данных в фабрике - запросить их и засетить
if (!$scope.games.list.length) {
$http(....).then(function(response)) {
Games.set(response.data)
}
}
});
Answer the question
In order to leave comments, you need to log in
The factory should request data from the server, for example, when creating (if the data does not change during operation), the factory creates a "singleton" so the loader at the start will be executed only 1 time.
If you need to get data in the controller, but there is none in the factory yet, then getGames should be asynchronous (for example, return a Promise).
If the data changes over time and the controller needs to respond to it, then you can do something like the factory sent out a pubsub message about the new data, and the controllers reacted to this and requested Games.get () again.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question