Angularjs 如何在两个控制器之间共享ajax返回的数据

Angularjs 如何在两个控制器之间共享ajax返回的数据,angularjs,angularjs-directive,angularjs-scope,angularjs-service,Angularjs,Angularjs Directive,Angularjs Scope,Angularjs Service,您好,我有两个控制器,其中一个我定义了一些函数来获取数据,我将数据存储在$scope.data1中,现在我想访问另一个命名控制器中的$scope.data1数据,以便在通过路由加载时可以访问其他页面上的数据。我可以如何操作 这是我的代码 commonApp.service('CommonServices',function($http){ this.getData=function(urlreq){ return $http({

您好,我有两个控制器,其中一个我定义了一些函数来获取数据,我将数据存储在$scope.data1中,现在我想访问另一个命名控制器中的$scope.data1数据,以便在通过路由加载时可以访问其他页面上的数据。我可以如何操作

这是我的代码

 commonApp.service('CommonServices',function($http){

            this.getData=function(urlreq){

                return $http({
                    method:"GET",
                    url   :urlreq
                });
            };
commonApp.controller('Controller1',function($scope,CommonServices,toaster){
           CommonServices.getData('dataurl1').success(function(getResponse){

                 $scope.data1=getResponse.success;  

           };
}
commonApp.controller('Controller2',function($scope,CommonServices,toaster){


                 $scope.data2= ????;    
//i want my $scope.data1 in $scop.data2. 


}




    });

您可以将共享数据保存在服务中。例如,如果将服务定义为工厂:

        commonApp.factory('commonFactory', ['$http', function ($http) { 

return {
            commonData: null
        };

    }]);
进入控制器后,您可以访问此commonData以存储和从中获取数据

第一控制器:

commonFactory.commonData = getResponse.success;
$scope.data2= commonFactory.commonData; 
第二控制器:

commonFactory.commonData = getResponse.success;
$scope.data2= commonFactory.commonData; 

我相信您正在寻找类似的东西,您使用相同的公共服务来存储一段数据,该数据可由访问该服务的任何控制器获取:

commonApp.service('CommonServices', function ($http) {
    this.shared = null;  // this is where the shared data would go

    this.getData = function (urlreq) {
        return $http({
            method: "GET",
            url: urlreq
        });
    };

    this.setSharedData = function (data) { // this sets the value of the shared data
        this.shared = data;
    };

    this.getSharedData = function () { // this retrieves the shared data
        return this.shared;
    }
});

commonApp.controller('Controller1', function ($scope, CommonServices, toaster) {
    CommonServices.getData('dataurl1').success(function (getResponse) {
        $scope.data1 = getResponse.success;
        CommonServices.setSharedData($scope.data1);

        // CommonServices.shared = $scope.data1; // this would also work
    });
});

commonApp.controller('Controller2', function ($scope, CommonServices, toaster) {
    $scope.data2 = CommonServices.getSharedData();

    // $scope.data2 = CommonServices.shared;  // this would also work
});
我基于您自己的示例代码,尽管我可能会以不同的方式构造东西。但这是基本点,我认为你的实际需要要复杂一点

请注意,您不需要在服务中使用setter和getter,尽管这可能有意义,这取决于是否需要添加诸如null检查和覆盖现有值之类的内容。您将在注释中看到,我已经包含了一个示例,说明如何在不使用设置和获取函数的情况下直接操作服务的属性

希望这有帮助,不要忘记投票并选择一个被接受的答案。