2014-12-04 73 views
0

我試圖保持我的代碼清潔,我注意到這在JavaScript中非常困難。話雖這麼說,我有一個角控制器,它調用了幾個不同的服務:如何通過角度控制器將參數傳遞給服務方法?

surchargeIndex.controller('SurchargeIndexController', function ($scope, customerService, templateService) { 
    $scope.customers = { Key: "", Value: "" }; 
    $scope.templates = { Key: "", Carrier: "", Service: "", RateType: "", SurchargeName: "", AccountNumber: "", RateGroup: "", OriginCountryCode: "", DestinationCountryCode: "", DomesticOrInternational: "", Zone: "", FuelType: ""} 

    customerService.getTest($scope); 
    templateService.getTemplates($scope, customerKey); 

}); 

服務:

surchargeIndex.service('customerService', [ 
    '$http', function($http) { 
     this.getTest = function($scope) { 
      return $http({ 
        method: "GET", 
        url: "api/Customer/GetTest", 
       }) 
       .success(function(data) { 
        $scope.customers = data; 
       }) 
       .error(function() { 
        $scope.error = "Failed to load customers!"; 
       }); 
     }; 


    } 
]); 

surchargeIndex.service('templateService', [ 
    '$http', function($http) { 
     this.getTemplates = function ($scope, customerKey) { 
      return $http({ 
       method: "GET", 
       url: "api/SurchargeTemplate/Get/" + customerKey 
      }) 
       .success(function (data) { 
        $scope.templates = data; 
       }) 
       .error(function() { 
        $scope.error = "Failed to load templates!"; 
       }); 
     }; 
    } 
]); 

我遇到的問題是與customerKey。我如何傳遞到一個按鈕的點擊參數:

<div class="dropdown"> 
    <select ng-model="customerKey"> 
     <option value="{{customer.Key}}" ng-repeat="customer in customers">{{customer.Value}}</option> 
    </select> 
    <button id="getTemplates" class="btn btn-primary" ng-click="getTemplates(customerKey)">Get Templates</button> 
</div> 

我想當前選定的選項傳遞給方法,這樣我可以就此採取行動。我得到的錯誤,當我運行這個雖然customerKey未定義。

有什麼建議嗎?

回答

5

而不是使用$ scope調用服務函數,您應該只傳遞服務正在使用的參數。

customerService.getTest($scope.customerKey); 

,並在服務:

surchargeIndex.service('customerService', [ 
    '$http', function($http) { 
     this.getTest = function(customerKey) { 
      console.log(customerKey); 
     }; 
    } 
]); 

,不要忘記向服務注入到控制器中

surchargeIndex.controller('SurchargeIndexController', ['$scope', 
'customerService', 'templateService', 
function ($scope, customerService, templateService) { 
     //... 
}]); 

,你也應該在你select標籤使用ng-options代替ng-repeat您的<option>標籤

+0

什麼當我將它們注入到控制器中時,就像你已經說明的那樣,將它們作爲參數傳遞給我時,會有什麼不同? – Robert 2014-12-04 13:36:01

+2

@Robert該服務不需要知道控制器$範圍。該服務應該被隔離並且只執行特定的操作。只有控制器應該能夠訪問$ scope並改變視圖。這是MVC方法。 – DanR 2014-12-04 13:38:04

+0

我需要將我從服務中獲得的值返回給控制器。我將如何做到這一點,而不需要設置$ scope? – Robert 2014-12-04 13:39:51

相關問題