3

嗨,我有兩個控制器,在一個我已經定義了一些函數來獲取數據,我將數據存儲在$ scope.data1中,現在我想訪問這個$ scope。 data1數據在另一個命名的控制器中,這樣我可以在通過路由加載時在其他頁面上訪問相同的數據。我該怎麼做。如何在兩個控制器之間共享ajax返回的數據

這裏是我的代碼是。

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. 


} 




    }); 

回答

1

您可以將共享數據保存在服務中。例如,如果您將服務定義爲工廠:

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

return { 
      commonData: null 
     }; 

    }]); 

在控制器中,您可以訪問此commonData以存儲並從中獲取數據。

第一控制器:

commonFactory.commonData = getResponse.success; 

第二個控制器:

$scope.data2= commonFactory.commonData; 
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 
}); 

我基於您r自己的示例代碼,但我可能會以不同的方式組織結構。但它是基本點,我認爲你的實際需求會更復雜一些。

請注意,您不需要在服務中使用setter和getter,但根據是否需要添加諸如空值檢查和覆蓋現有值之類的內容,這可能很有意義。您將在評論中看到我已經包含了一個示例,說明如何在沒有設置和獲取功能的情況下直接操作服務的屬性。

希望這會有所幫助,並且不要忘記upvote並選擇一個可接受的答案。