【问题标题】:AngularJS $http use response in multiple controllersAngularJS $http 在多个控制器中使用响应
【发布时间】:2015-04-30 21:06:10
【问题描述】:

我有一个应用程序,我在其中加载一堆专辑的一部分,然后当用户单击每个单独的专辑时,他们会获取专辑的详细信息,例如歌曲等。现在我正在从数据库中提取数据,但是这样做两次,一次在 ProjectsCtrl 中显示所有专辑,然后再次在 ProjectsDetailCtrl 中显示单个专辑信息。我觉得有一种更快的方法可以做到这一点,但不知道如何保存第一次的数据以便在第二个控制器中再次使用

(function() {
    var app = angular.module('chp', ['ngRoute', 'projectControllers']);

    app.config(['$routeProvider',
      function($routeProvider) {
        $routeProvider.
          when('/', {
            templateUrl: 'partials/directory.html',
            controller: 'ProjectsCtrl'
          }).
          when('/album/:slug', {
            templateUrl: 'partials/album.html',
            controller: 'ProjectDetailCtrl'
          }).
          otherwise({
            redirectTo: '/'
          });
      }]);

    var projectControllers = angular.module('projectControllers', []);

    projectControllers.controller('ProjectsCtrl', ['$scope', '$http',
      function ($scope, $http) {
        $http.get('/get_albums').success(function(albums) {
            $scope.projects = albums;
            $scope.filters = { };
        });
      }]);



    projectControllers.controller('ProjectDetailCtrl', ['$scope', '$http', '$routeParams', '$sce',
      function($scope, $http, $routeParams, $sce) {


        $http.get('/get_albums').success(function(albums) {
            $scope.projects = albums;

            for(var i = 0; i < $scope.projects.length; i++) {
                if($scope.projects[i].slug === $routeParams.slug){
                    $scope.album = $scope.projects[i];
                    $scope.albumIdx = i;
                    break;
                }
            }    

            $scope.project = albums[$scope.albumIdx];

            $scope.showVideo = function(id) {
                var videoCode = $(this)[0].song.video;
                // videoCode = '<iframe width="560" height="315" src="'+video+'" frameborder="0" allowfullscreen></iframe>';
                $('#myModal .flex-video').html(videoCode);
                $('#myModal .track-number').html('<span style="color: #f86081; display: inline-block; margin-right: 4px;">' + ($(this)[0].$index+1) + '.</span> ' + $(this)[0].song.title);
                $('#myModal').foundation('reveal', 'open');
            }

        });

    }]);
})();

【问题讨论】:

    标签: angularjs angularjs-controller angularjs-http


    【解决方案1】:

    如果$http.get('/get_albums') 生成了两个控制器所需的所有数据,那么听起来您只需要使用缓存:

    $http.get('/get_albums', { cache: true })....
    

    在两个控制器中使用它,您只会访问服务器一次。

    最好将其放置在工厂中,以便数据检索逻辑仅在一个位置,但这不是绝对要求。

    【讨论】:

      【解决方案2】:

      我会选择在两个控制器中注入 $rootScope

      myApp.controller('controllerA', function($rootScope){
          $rootScope.sharedData = {album: ...};
          ...
      });
      

      或者创建一个值并将其注入两个控制器中以传递此数据:

      myApp.value('myValues', '{sharedData: {}}');
      myApp.controller('controllerA', function(myValues){
          myValues.sharedData.album = ...
          ...
      });
      

      这基本上是同一个问题,并且有很好的答案和cmets:

      Best way to pass data between ngRoute controllers (from one view to the next)

      【讨论】:

        【解决方案3】:

        是的,对于这种情况,服务或工厂都可以。您还可以将先前输入的数据存储在本地存储中,例如使用该服务。基本上这是未来改进的更好方法。

        作为一种更简单的方法,您可以简单地使用 $rootScope。它可以在您希望的所有控制器中使用。

        只需将其注入控制器或应用程序本身。

        app.controller('myCtrl', function($rootScope){
            $rootScope.myStoredValues = {...};
        });
        

        app.run(function($rootScope){
            $rootScope.root = $rootScope; 
            $rootScope.myStoredValues = {...};
            // this way you don't need to inject it into controller, 
            // it will be available there via $scope.root.myStoredValues
        });
        

        【讨论】:

          【解决方案4】:
          app.factory('ProjectService', function ($http) {
            var projects = []
            return{
          
              getProjectList: function(){
                $http.get('/get_albums').success(function(albums) {
                  projects = albums;
                });
              },
          
              getProject: function( id ){
                // here you can select the already existing project from the above list "projects" by using the Id passed
              }
          
            }
          
          });
          

          您可以将此服务包含在控制器中并使用它们来获取专辑列表和单个专辑

          【讨论】:

            猜你喜欢
            • 2015-03-11
            • 1970-01-01
            • 2016-04-01
            • 2021-12-19
            • 1970-01-01
            • 2013-08-28
            • 1970-01-01
            • 1970-01-01
            • 2015-10-28
            相关资源
            最近更新 更多