Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static row above knockout.js observable array table

I have a html table and the rows come form an observable array....

 <tbody data-bind="foreach: TableArray">
     <tr>
         <td data-bind:"text: Item1"></td>

etc....

How can I skip the first row... so I can add a static row (not a header) to the top of the table.

<tbody data-bind="foreach: TableArray">
     <tr> 
        <td> Static Row </td>
     </tr>
     <tr>
         <td data-bind:"text: Item1"></td>
like image 381
user3147424 Avatar asked Jan 29 '14 18:01

user3147424


1 Answers

The secret is in the containerless foreach markup. Check "Note 4" of the following link:

http://knockoutjs.com/documentation/foreach-binding.html

Here's a fiddle showing a basic example.

http://jsfiddle.net/internetH3ro/M9f4D/7/

Basic view model:

function ViewModel() {
    var self = this;
    self.items = [{
        firstName: 'James',
        lastName: 'McConnell'
    },{
        firstName: 'Scott',
        lastName: 'Hanselman'
    },{
        firstName: 'Bill',
        lastName: 'Gates'
    }];
}

HTML markup:

<table>
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
    </tr>
    <!-- ko foreach: items -->
    <tr>
        <td><span data-bind="text: $data.firstName"></span></td>
        <td><span data-bind="text: $data.lastName"></span></td>
    </tr>
    <!-- /ko -->
</table>

So you just wrap the content you want repeated in a comment, and Knockout will repeat that content for each element in your collection. Pretty nifty, I wish Angular had something like this.

like image 62
James McConnell Avatar answered Oct 20 '22 19:10

James McConnell