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

时间:2014-08-27 11:50:46

标签: angularjs angularjs-directive angularjs-scope angularjs-service

嗨我有两个控制器,其中一个我定义了一些函数来获取数据,我将数据存储在$ 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. 


}




    });

2 个答案:

答案 0 :(得分:3)

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

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

return {
            commonData: null
        };

    }]);

在控制器中,您可以访问此commonData以存储并从中获取数据。

第一个控制器:

commonFactory.commonData = getResponse.success;

第二控制器:

$scope.data2= commonFactory.commonData; 

答案 1 :(得分:2)

我相信您正在寻找类似这样的内容,您可以使用相同的公共服务来存储可以访问该服务的任何控制器获取的数据:

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检查和覆盖现有值等内容的需要,它可能有意义。您将在评论中看到我已经包含了一个示例,说明如何在不设置和获取函数的情况下直接操作服务的属性。

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

相关问题