从ko.observableArray动态设置表列

Tan*_*ner 7 knockout.js knockout-mvc

我试图根据ko.observableArray返回的列未预先确定的位置输出数据表.

来自我的observableArray的项目样本self.userData()[0]将是:

Object {
        RowNum: 1, 
        ID: "123", 
        Surname: "Bloggs", 
        Forename: "Joe", 
        Address line 1: "1 Park Lane"
}
Run Code Online (Sandbox Code Playgroud)

根据用户选择输出的内容,这些列每次都不同.

我希望输出中的列标题由数组中的内容确定,所以我想要的输出是:

<table>
   <thead>
      <tr>
         <th>RowNum</th>
         <th>ID</th>
         <th>Surname</th>
         <th>Forename</th>
         <th>Address line 1</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td>1</td>
         <td>123</td>
         <td>Bloggs</td>
         <td>Joe</td>
         <td>1 Park Lane</td>
      </tr>
      <!-- repeated for each row -->
   </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

我知道我可以foreach用来重复行和列,但我不确定如何根据我的内容动态引用它observableArray.

目前我有这个基本结构:

<table>
    <thead> 
        <tr data-bind="foreach: userData [property name] ">
            <th>
               <span data-bind="text: [property name]"></span>
            </th>                   
        </tr>
    </thead>
    <tbody data-bind="foreach: userData">                
        <tr data-bind="foreach: userData [property name]>
            <td data-bind="text: [property value]">                            
            </td>                        
        </tr>
    </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

Dam*_*ien 17

你可以这样做:

JS:

var VM = function () {
    var self = this;
    self.items = ko.observableArray();
    self.columnNames = ko.computed(function () {
        if (self.items().length === 0)
            return [];
        var props = [];
        var obj = self.items()[0];
        for (var name in obj)
            props.push(name);
        return props;


    });

};
var vm = new VM();

ko.applyBindings(vm);

vm.items.push({
    'Name': 'John',
    'Age': 25
});
vm.items.push({
    'Name': 'Morgan',
    'Age': 26
});
Run Code Online (Sandbox Code Playgroud)

查看:

<table>
    <thead>
        <tr data-bind="foreach: columnNames">
            <th> <span data-bind="text: $data"></span>

            </th>
        </tr>
    </thead>
    <tbody data-bind="foreach: items">
        <tr data-bind="foreach: $parent.columnNames">
            <td data-bind="text: $parent[$data]"></td>
        </tr>
    </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

看小提琴

我希望它有所帮助.