This is one of the common doubts when starting with AngularJS. By your requirement, I believe your best option is to create a service that retrieves the movie list and then use this service in both controllerA
and controllerB
.
module.factory('youtube', function() {
var movieListCache;
function getMovies(ignoreCache) {
if (ignoreCache || !movieListCache) {
movieListCache = $http...;
}
return movieListCache;
}
return {
get: getMovies
};
});
Then you just inject this service in both controllers.
module.controller('controllerA', ['youtube', function(youtube) {
youtube.get().then(function doSomethingAfterRetrievingTheMovies() {
});
}]);
module.controller('controllerB', ['youtube', function(youtube) {
youtube.get().then(function doAnotherThingAfterRetrievingTheMovies() {
});
}]);
If you need controllerA to manipulate the info before you use it in B then you could create more methods in the service. Something like this:
module.factory('youtube', function($q) {
var movieListCache,
deferred = $q.defer();
function getMovies(ignoreCache) {
if (ignoreCache || !movieListCache) {
movieListCache = $http...;
}
return movieListCache;
}
function getChangedMovies() {
return deferred.promise;
}
function setChangedMovies(movies) {
deferred.resolve(movies);
}
return {
get: getMovies,
getChanged: getChangedMovies,
setChanged: setChangedMovies
};
});
If you don't know what $q
is, take a look at the docs. This is mandatory to handle async operations.
Anyway, there are some other ways of accomplishing this task too:
- You could save the videos at
$rootScope
- If the controllers are father and son the you could use require to retrieve each other controller
IMHO, #1 is a generic solution; I'd use it only if there is no other option. And #2 is useful if you have an intrinsic need to communicate between these controllers, such as configuring or letting one know about the other's existence. There is a example here.
What you want to do is to share stateful singleton information; therefore, a service is the way to go.