Reputation: 241
I have a HTML table that works fine without DataTables.
However, I want to implement DataTables so that I can use the filtering/search functionality and also add/remove columns.
How do I get it working with Knockout?
var ViewModel = function() {
$('#myTable').DataTable({
ajax: {
url: this.taskRecords()
}
});
this.taskRecords = ko.observableArray([
{
EntityCode: "name",
EntityName: "name desc23",
TagName: "L1",
TaskList: [
{
TaskName: "TaskABC",
TaskRecordList: [
{
StatusFlagName: "OK"
},
{
StatusFlagName: "TEST"
}
]
},
{
TaskName: "TaskDEF",
TaskRecordList: [
{
StatusFlagName: "Error"
}
]
}
]
}
]);
};
ko.applyBindings(new ViewModel());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table id="myTable" class="table table-hover table-bordered">
<thead>
<tr>
<th>Entity Code</th>
<th>Entity name</th>
<th>Control Level</th>
</tr>
</thead>
<tbody id="sortable" data-bind="foreach: taskRecords">
<tr class="ui-state-default">
<td class="ui-state-default" data-bind="text: EntityCode"></td>
<td class="ui-state-default" data-bind="text: EntityName"></td>
<td class="ui-state-default" data-bind="text: TagName"></td>
<!--ko foreach: TaskList-->
<td>
<div data-bind="text: TaskName"></div>
<table>
<tbody>
<!--ko foreach: TaskRecordList-->
<tr>
<td data-bind="text: StatusFlagName"></td>
</tr>
<!--/ko-->
</tbody>
</table>
</td>
<!--/ko-->
</tr>
</tbody>
</table>
Upvotes: 0
Views: 3465
Reputation: 494
It looks like you are trying to bind the data twice:
And there is also another problem: DataTable does not like to add table columns without corresponding header.
I got it to work with two modifications:
a. No data binding with DataTable, just init with:
$('#myTable').DataTable({
responsive: true
});
b. Add <th>Tasks</th>
to the table header
Complete solution: https://codepen.io/DonKarlssonSan/pen/mMVvME/
Upvotes: 2