2014-03-05 27 views
0

我有一個可觀察數組,我在select元素中顯示,例如,如果我有4個元素在數組中,那麼我將有4個選擇元素。如何通過選擇元素更新Observable Array的值

當我改變選擇列表中的項目時,可觀察數組似乎沒有改變。

請幫助我如何更新observable數組。

的一樣的jsfiddle是here

HTML代碼

<div> 
    <div> 
     <table> 
      <th>Name</th> 
      <th>Age</th> 
      <th>Country</th> 
      <tbody data-bind="foreach: players"> 
       <tr> 
        <td data-bind="text: name"></td> 
        <td data-bind="text: age"></td> 
        <td data-bind="text: country"></td> 
        <td data-bind="text: trophies"></td> 
        <td> 
         <button data-bind="click: $root.editPlayers">Edit</button> 
        </td> 
       </tr> 
      </tbody> 
     </table> 
    </div> 
    <div data-bind="with: editPlayer"> 
     <h3>Edit</h3> 
Name: 
     <input type="text" data-bind="value: name" /> 
     <br/>Age: 
     <input type="text" data-bind="value: age" /> 
     <br/>Country: 
     <input type="text" data-bind="value: country" /> 
     <span data-bind="foreach: trophies"> 
      <br/>Tropies: 
      <select data-bind="options: $root.trophiesList, value:$data, optionsCaption:'Choose..'"></select>  
     </span> 

    </div> 
</div> 

JavaScript代碼

var player = function (name, age, country, trophyArray) { 
    this.name = ko.observable(name); 
    this.age = ko.observable(age); 
    this.country = ko.observable(country); 
    this.trophies = ko.observableArray(trophyArray); 
}; 

var playerModel = function() { 
    var self = this; 
    self.players = [ 
     new player('Roger', 32, 'swiss', ['AO','FO','WB','US']), 
     new player('Murray', 28, 'Scott', ['WB','US'])]; 

    self.editPlayer = ko.observable(); 
    self.trophiesList = ['AO','US','FO', 'WB']; 

    self.editPlayers = function (player) { 
     self.editPlayer(player); 
    } 

} 

ko.applyBindings(new playerModel()); 
+0

JSFiddler指着一個老版本,我已經更新了鏈接再次 – Swamy

+1

你的模式是錯誤的。你不會爲每個選項做一個選項,只需使用可觀察數組設置選項參數,那麼值參數應該與selectedTrophy類似。再次檢查文檔 –

+0

@ bto.rdz我有一個獎盃的列表,我在一個單獨的select元素中顯示每個獎盃,允許每個都改變。可能我也會嘗試多選擇選項。 – Swamy

回答

0

您好我已經創建了一個更新搗鼓你

self.players = [ 
    new player('Roger', 32, 'swiss', [{key: ko.observable('AO')},{key:ko.observable('FO')},{key:ko.observable('WB')},{key: ko.observable('US')}]), 
    new player('Roger', 32, 'swiss', [{key: ko.observable('AO')},{key:ko.observable('FO')},{key:ko.observable('WB')},{key: ko.observable('US')}])]; 

http://jsfiddle.net/M8m8R/4/

希望這有助於

1

刪除下列標記:

<span data-bind="foreach: trophies"> ,截止</span>標籤。

然後使用selectedOptions結合來管理獎盃陣列:然後

<br/>Tropies: 
    <select data-bind="options: $root.trophiesList, selectedOptions:trophies, optionsCaption:'Choose..'" multiple="true" size="10"></select>  

用戶可以選擇/取消選擇多個獎盃。

+0

謝謝。多選擇服務的目的,但我想每個數組元素的單下拉,並注意可觀察數組的每個項目應該是可觀察的,如上例中。 – Swamy