What I have done. I retrieve a list of videos from youtube api with json in a controllerA with specific directive. The json contain the list of video and the video itself details.
What I want to do. When click on a video, I want the video's details display in another ng-view with other controllerB with using the json data I request before.
So my question is How to pass the data from controllerA to controllerB
Note - $http service is use in controllerA
Inside the . component in the model that you just passed data into (ModelOne), use the same name as you declared in the HTML ('data') and add it into a bindings object (note: bindings, plural). You can use '<', '=', '&' or '@' depending on what you need. And then repeat step 2 and 3 for the next child component.
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:
$rootScope
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With