0

我正在使用'getPickupSchedules'指令來根據用戶郵政編碼填充計劃。用戶輸入5位數的郵政編碼後,我會執行$http.get來檢索其zip的計劃並生成一個select元素。每個元素的值都是它們的主鍵,當我檢查元素時,但是當表單被提交時,pickup_schedule的值作爲包含所有其他值的對象返回,而不是pickup_id,這導致我在服務器上發生錯誤側。我知道我可以解析它以獲取正確的數據,但是有些事情告訴我不應該這樣做,或者我可能錯過了或做錯了什麼。ngOptions提交對象而不是選項值

app.directive('getPickupSchedules', function($http){     

    return {                  
     restrict: 'A',               
     replace: true,               
     templateUrl: STATIC_URL + 'templates/directives/get_pickup_schedules.html',      

     link: function(scope, elem, attrs) {                      

      scope.$watch('formData.zip', function() {        
       zip = scope.formData.zip           

       if (typeof zip !== 'undefined' && zip.length == 5)    
       {                 

        $http.get('/get_schedules/' + zip)   
         .then(function (results){         
          var pu = results.data         
          scope.pickupSchedules = results.data     
          console.log(scope.pickupSchedules);     
          scope.formData.pickupSchedules = scope.pickupSchedules[0] 

        });               
       }                 
      });                 

     }                   
    } 

get_pickup_schedules.html

<div>                    
    <select                  
      data-ng-options="(pickup.route + ' - ' + pickup.date) for pickup in pickupSchedules track by pickup.pickup_id" 
      ng-model="formData.pickup_schedule">         
      <option value="">Select a pickup schedule</option>     
    </select>                  
</div> 

元件上檢查:

<select data-ng-options="(pickup.route + ' - ' + pickup.date) for pickup in pickupSchedules track by pickup.pickup_id" ng-model="formData.pickup_schedule" class="ng-valid ng-dirty"> 
<option value="" class="">Select a pickup schedule</option> 
<option value="8297">Route 1 - 2014-06-18</option> 
<option value="8298">Route 2 - 2014-06-25</option> 
<option value="9543">Route 3 - 2014-07-02</option> 
<option value="9544">Route 4 - 2014-07-09</option> 
</select> 

我已綁定的所有形式的數據到一個formData變量。這裏是console.logformData.pickup_schedule這是返回一個對象,而不是主鍵在選項值中給出。

pickup_schedule: Object 
date: "2014-06-25" 
driver: null 
pickup_id: 8298 
route: "Section 15" 

回答

0

我有一個很艱難的時期之後,你在說什麼......但我認爲你正在嘗試做的是這樣的:

<select data-ng-options="pickup.pickup_id as (pickup.route + ' - ' + pickup.date) for pickup in pickupSchedules" ng-model="formData.pickup_schedule"> 
+0

的工作,謝謝。這些選項將選項值設置爲1,2,4,5等。我擁有它的方式具有實際的PK值。我不太明白爲什麼這種方法可行,但提交的數據是PK的價值。 – Austin

+0

當你使用'as'時,無論在左邊的是什麼,分配給'ng-model',無論在右邊的是標籤。 – dave

+0

有道理。對我來說,看起來很奇怪,HTML中的選項值顯示的方式與之前提交的不同。再次感謝。我是Angular的新手,所以也許我只是沒有正確地考慮它。 – Austin

相關問題