AngularJS将数据从一个控制器传递到另一个控制器
AngularJS将数据从一个控制器传递到另一个控制器
我做了什么。
我在一个带有特定指令的controllerA中使用json从youtube api检索视频列表。json包含视频列表和视频本身的细节。
我想要做什么。
当单击视频时,我希望视频的详细信息显示在另一个ng-view中,使用之前请求的json数据的other controllerB。
我的问题是
如何将数据从controllerA传递到controllerB
注意-在controllerA中使用了$http服务
admin 更改状态以发布 2023年5月23日
在开始学习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() { }); }]);
如果您需要在使用B之前在控制器A中操纵信息,则可以在服务中创建更多方法。例如:
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
中保存视频 - 如果控制器是父子关系,则可以使用require来检索彼此控制器
以我个人的看法,#1是通用解决方案;仅在没有其他选项时才会使用它。如果您有内在需求在这些控制器之间进行通信(例如配置或让一个知道另一个的存在),则#2非常有用。这里有一个示例。
您想要做的是共享有状态的单例信息;因此,服务是正确的选择。