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

时间:2013-04-02 11:49:02

标签: javascript angularjs

我做了什么。 我在带有特定指令的controllerA中使用json从youtube api中检索视频列表。 json包含视频列表和视频本身的详细信息。

我想做什么。 点击视频时,我希望视频的详细信息显示在另一个ng-view中,其他控制器B使用我之前请求的json数据。

所以我的问题是 如何将数据从controllerA传递到controllerB

注意 - $ http服务用于controllerA

1 个答案:

答案 0 :(得分:15)

这是从AngularJS开始时常见的疑问之一。根据您的要求,我认为您最好的选择是create a service检索电影列表,然后在controllerAcontrollerB中使用此服务。

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() {
  });
}]);

如果在B中使用它之前需要controllerA来操作信息,那么您可以在服务中创建更多方法。像这样:

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是什么,take a look at the docs。这是处理异步操作的必要条件。

无论如何,还有其他一些方法可以完成这项任务:

  1. 您可以将视频保存在$rootScope
  2. 如果控制器是父子,你可以使用require来检索彼此的控制器
  3. 恕我直言,#1是通用解决方案;只有在没有其他选择的情况下我才会使用它。如果您对这些控制器之间的通信有内在需求,例如配置或让人知道对方的存在,那么#2非常有用。有example here

    你想要做的是分享有状态的单身人士信息;因此,服务是可行的方式。