2016-02-05 22 views
0

廣播HTTP POST方法的數據我使用相同的HTTP方法在不同的控制器等下面的示例:如何在angularjs

服務:

var method="sampleMethod" 
    HotalStatisticService.GetReservations = function (data) { 
     return $http({ 
      method: 'POST', 
      data: data, 
      cache: false, 
      url:'http://sample.com/'+method 
     }); 
    } 

第一控制器

.controller("SampleACtrl", function ($scope,HotalStatisticService) { 
    HotalStatisticService.GetReservations({start:start, end:end, type:type}) 
     .success(function (data) { 
     $scope.sampleA=data; 
     }) 
} 

第二控制器

.controller("SampleBCtrl", function ($scope,HotalStatisticService) { 
    HotalStatisticService.GetReservations({start:start, end:end, type:type}) 
      .success(function (data) { 
      $scope.sampleB=data; 
      }) 
    } 

如何在唯一的控制器中使用here方法?

+0

對不起,你能澄清一下你想要的嗎? –

+0

如何在不同的控制器之間傳輸數據,例如廣播,發出 –

+0

這兩個控制器有兩個不同的模塊? –

回答

0

讓我說,使用工廠的其他解決方案可能是一個更好的解決方案。使用服務也是一個不錯的選擇。

另一個可能最簡單的方法是使用下面的$ rootScope.Answer。

你基本上想要做的是在兩個控制器之間共享數據。根據您評論的回覆,這兩個控制器屬於同一個模塊。您可以在此使用$rootScope作爲通用點。

如您所見,我已將$rootScope作爲依賴項添加到兩個控制器中,並在第二個div中簡單地打印txt變量。

JS代碼

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

app.controller('ACtrl', function($scope,$rootScope) { 
    $scope.name = 'This is Controller A '; 
    $scope.execute = function() { 
    alert('Executed!'); 
    } 
    $rootScope.txt="Hi there from the other side"; 
}); 

app.controller('BCtrl', function($scope,$rootScope) { 
    $scope.name = 'This is Controller B '; 

}); 

HTML

<div ng-controller="ACtrl"> 
    <p>Hello {{name}}!</p> 

    </div> 


    <div ng-controller="BCtrl"> 
    <p>Hello {{name}}!</p> 
    {{txt}} 
    </div> 

這裏是DEMO

0

我會做的是創建一個factory service來處理您的HTTP請求,和T母雞將該服務注入到您的控制器中...代碼看起來像這樣:

var app = angular.module('sampleApp');

app.factory('sampleFactory', ['$http', 
    function($http) { 

     return { 
      getData: function(success, fail) { 
       if (_dataStore) { 
        success(_dataStore); 
       } 

       $http({ 
        //fill in your params here 
       }) 
       .then(
       function successCallback(response) { 
        //store data in the _dataStore object 
        success(response) 
       }, fail(response)) 
      }, 

      _dataStore: {} 
     } 
    } 
]); 

app.controller('SampleACtrl', ['$scope', 'sampleFactory', 
    function($scope, sampleFactory) { 
     $scope.sampleA = sampleFactory.getData(success, fail); 
    } 
]); 

app.controller('SampleBCtrl', ['$scope', 'sampleFactory', 
    function($scope, sampleFactory) { 
     $scope.sampleB = sampleFactory.getData(success, fail); 
    } 
]); 

這樣做的主要思想是,您只做一次HTTP請求,然後將數據作爲對象存儲在工廠中。當您在該對象上調用getData()函數時,您將獲得實際已在工廠中的內容(意味着請求已完成),否則您將發出請求。作爲您的響應功能,您可以傳入2個函數(成功或失敗),作爲$ http調用的函數。這遠遠不是100%好,還有很多改進(在那裏添加$ q以返回承諾等),但這是一個正確方向的開始。
長話短說:USE FACTORIES!