2012-12-27 107 views
0

這是示例代碼knockout.js:如何添加列到表

<h2>Your seat reservations</h2> 

<table> 
    <thead><tr> 
     <th>Passenger name</th><th>Meal</th><th>Surcharge</th><th></th> 
    </tr></thead> 
    <tbody data-bind="foreach: seats"> 
    <tr> 
     <td data-bind="text: name"></td> 
     <td data-bind="text: meal().mealName"></td> 
     <td data-bind="text: meal().price"></td> 
    </tr>  
</tbody> 
    <tbody><button data-bind="click: addSeat">Reserve another seat</button></tbody> 
</table> 

JS:

// Class to represent a row in the seat reservations grid 
function SeatReservation(name, initialMeal) { 
    var self = this; 
    self.name = name; 
    self.meal = ko.observable(initialMeal); 
} 

// Overall viewmodel for this screen, along with initial state 
function ReservationsViewModel() { 
    var self = this; 

    // Non-editable catalog data - would come from the server 
    self.availableMeals = [ 
     { mealName: "Standard (sandwich)", price: 0 }, 
     { mealName: "Premium (lobster)", price: 34.95 }, 
     { mealName: "Ultimate (whole zebra)", price: 290 } 
    ];  

    // Editable data 
    self.seats = ko.observableArray([ 
     new SeatReservation("Steve", self.availableMeals[0]), 
     new SeatReservation("Bert", self.availableMeals[1]) 
    ]); 

    self.addSeat = function() { 
     self.seats.push(new SeatReservation("12321", self.availableMeals[0])); 
    } 
} 

ko.applyBindings(new ReservationsViewModel()); 

驗證碼好工作了add列。但我需要專欄,這是可能的嗎?在ReservationViewModel

+0

我很困惑,要添加列,但不是行,爲什麼呢? – paritosh

+0

我很震驚,但我需要這個 – Mediator

+0

我認爲無容器綁定將成爲您的朋友 –

回答

1

添加以下行並替換你的頭下面

self.Columns = ko.observableArray([{ ColumnName: "Header1" }, { ColumnName: "Header2"}]); 


<tr data-bind="foreach: Columns"> 
      <th data-bind="text: ColumnName> 
       Passenger name 
      </th> 
     </tr> 

希望HTML部分,這將幫助你