2015-04-03 39 views
0

我有一個下拉,基於我創建的jSON對象填充。我正在嘗試將文本值「wineSupplier」傳遞給下拉菜單中的文本選項,但是它將POST中的數組值傳遞給節點。角落傳遞下拉值而不是實際的字符串到節點

因此,如果我的下拉具有以下選項:

  • Ç
  • d

    和我選擇 「C」 的2值是通過,我希望能夠收到「C」

代碼段從wines.ejs:

  <form action="/createWine" method="POST"> 
       <p>Select the Wine Supplier:</p> 
       <select name="wineSupplier" ng-model="supplierSelection" ng-options="supplier as supplier.supName for supplier in suppliers"> 
       </select> 
       <label>Wine Name:</label> 
       <input type="text" name="wineName" placeholder="Wine Name"/> 
       <label>Wine Producer:</label> 
       <input type="text" name="wineProducer" placeholder="Wine Producer"/> 
       <label>Wine Colour:</label> 
       <input type="text" name="wineColour" placeholder="Wine Colour"/> 
       <label>Wine Type:</label> 
       <input type="text" name="wineType" placeholder="Wine Type"/> 
       <label>Wine Country:</label> 
       <input type="text" name="wineCountry" placeholder="Wine Country"/> 
       <p> 
        <button type="submit" class="btn">Submit</button> 
       </p> 
      </form> 

代碼從app.js

//Create a new wine objhect 

app.post('/createWine', function(request, response) { 
    //create and save a wine model 
    var wine = new myWine({ 
     wineSupplier: request.body.wineSupplier, 
     wineName: request.body.wineName, 
     wineProducer: request.body.wineProducer, 
     wineColour: request.body.wineColour, 
     wineType: request.body.wineType, 
     wineCountry: request.body.wineCountry 
    }); 

    //save to model 
    wine.save(function(err, model) { 
     if (err) { 
      response.send(504, 'There was an error'); 
     } 
     else { 
      response.redirect('/'); 
     } 
    }); 
}); 
+0

乍一看看起來不錯。 「供應商」是什麼樣的? – ryanyuyu 2015-04-03 19:22:25

+0

ng-options =「supplier.supName as supplier.supName for supplier in supplier – 2015-04-03 19:23:10

+0

它是因爲你的值是根據你的代碼設置爲數組供應商的。所以選擇C就是該數組的索引2,這就是爲什麼。 – 2015-04-03 19:24:14

回答

2

當你想<option> S的實際值和<select>自己是從模型的數值剪斷,你應該使用track by

沒有track by,AngularJS將給出<options>數值,它將用來跟蹤哪些選擇屬於哪個數組項。

angular.module('app', []) 
 
.controller('C', ['$scope', function ($scope) { 
 
    $scope.suppliers = [{supName:'A'},{supName:'B'}, {supName:'C'}, {supName:'D'}]; 
 
}]); 
 
      
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script> 
 
<div ng-app="app" ng-controller="C"> 
 
    <select name="wineSupplier" ng-model="supplierSelection" 
 
      ng-options="supplier.supName for supplier in suppliers track by supplier.supName"> 
 
    </select> 
 
</div>

在另一方面,好像你是有點濫用使用它只是提供表單的一部分,並使用純提交提交值角。理想情況下,您的所有控件都應綁定到模型中的字段,並且您應該使用AngularJS執行提交到服務器。如果你這樣做,你將不需要使用track by

+0

這是行得通的!謝謝sooooo,從一個小時的頭疼時節省了一個新手。 – Freekstile 2015-04-03 19:50:40

相關問題