AngularJS pass data from controller to another controller

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


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.

    链接地址: http://www.djcxy.com/p/77822.html

    上一篇: AngularJS:$ scope没有定义?

    下一篇: AngularJS将数据从控制器传递到另一个控制器