AngularJS transfers data from the controller to another controller

What I've done. I get a list of videos from youtube api with json in controller A with a specific directive. Json contains a list of videos and the video information itself.

What do I want to do. When you click on the video, I want the video information to be displayed in a different ng view with another controller B using the json data that I requested before.

So my question is: How to transfer data from controller A to controller B

Note. The $ http service is used in the controller.

+5
source share
1 answer

AngularJS. , , - , , controllerA, controllerB.

module.factory('youtube', function() {
  var movieListCache;

  function getMovies(ignoreCache) {
    if (ignoreCache || !movieListCache) {
      movieListCache = $http...;
    }

    return movieListCache;
  }

  return {
    get: getMovies
  };
});

.

module.controller('controllerA', ['youtube', function(youtube) {
  youtube.get().then(function doSomethingAfterRetrievingTheMovies() {
  });
}]);

module.controller('controllerB', ['youtube', function(youtube) {
  youtube.get().then(function doAnotherThingAfterRetrievingTheMovies() {
  });
}]);

A , B, . - :

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
  };
});

, $q, . .

, :

  • $rootScope
  • , .

IMHO, # 1 - ; , . №2 , , , . .

, , - Singleton Singlepoint; - .

+15

All Articles