2016-07-23 69 views
-1

試圖找出如何設置淘汰賽表中的單選按鈕綁定。我希望選擇表格上的單選按鈕。整個選定的記錄在模型中可用。不太確定如何設置無線電輸入上的綁定。我假設我需要使用$ parent和一個函數進行值綁定?選擇obsservableArray從表中淘汰記錄

這裏是小提琴。 (選定的記錄沒有做任何事情,現在我想選擇的單選按鈕,當它被填充)

https://jsfiddle.net/othkss9s/5/

HTML

<table> 
<thead> 
    <tr> 
    <th>Select</th> 
    <th>First</th> 
    <th>Last</th> 
    <th>Dept</th> 
    </tr> 
</thead> 
    <tbody data-bind='foreach: employees'> 
    <tr> 
     <td><input type="radio" name="employees"></td> 
     <td data-bind='text: first'></td> 
     <td data-bind='text: last'></td> 
     <td data-bind='text: dept'></td> 
    </tr> 
    </tbody> 
</table> 

<div data-bind="with: selectedRow"> 
<h2> 
    Selected Record 
    </h2> 
<p> 
    First: <span data-bind="first" ></span> 
</p> 
<p> 
    Last: <span data-bind="last" ></span> 
</p> 
<p> 
    Dept: <span data-bind="dept" ></span> 
</p> 

</div> 

JS

function employee(first, last, dept) { 
    this.first = ko.observable(first); 
    this.last = ko.observable(last); 
    this.dept = ko.observable(dept); 
} 

function model() { 
    var self = this; 
    this.employees = ko.observableArray(""); 
    this.selectedRow = ko.observable({}); 

}; 

var myViewModel = new model(); 

$(document).ready(function() { 
    ko.applyBindings(myViewModel); 
    myViewModel.employees.push(
    new employee("Bob","Jones", "Hr") 
); 
    myViewModel.employees.push(
    new employee("Sarah","Smith", "It") 
); 
    myViewModel.employees.push(
    new employee("John","Miller", "It") 
); 


}); 

回答

2

你必須執行兩個步驟才能使您的代碼正常工作。

首先,應用綁定,以單選按鈕:

<input type="radio" data-bind="checked: $root.selectedRow, checkedValue: $data" /> 

checkedValue應包含對應當前無線電按鈕的實際值。在這種情況下,我們將$data變量稱爲整個員工對象,而不是簡單(標量)值。

checked綁定應引用包含當前選定員工的observable。

其次,糾正其中selectedRow屬性定義行:

this.selectedRow = ko.observable(); 

千萬不要錯過空對象爲默認值。否則with綁定將無法正常工作。

通過在顯示選定員工的第二個塊中修改綁定的語法,您將得到類似this的東西。