I am having a viewmodel and an associated template as below.
var AilmentItem = function () {
this.SelectedAilment = ko.observable();
}
function AilmentsViewModel() {
this.Ailments = ko.observableArray([new AilmentItem()]);
this.AilmentsType = ko.observableArray([{ Name: 'Diabetes' }, { Name: 'Arthritis' }, { Name: 'High BP'}]);
}
HTML script
<script type="text/javascript">
$(function () {
var AilmentsVM = new AilmentsViewModel();
ko.applyBindings(AilmentsVM, $('#Ailments')[0]);
});
</script>
<div id="Ailments">
<div>
<table>
<tbody data-bind='template: { name: "ailmentRowTemplate", foreach: Ailments }'>
</tbody>
</table>
</div>
</div>
<script type="text/html" id="ailmentRowTemplate">
<tr>
<td><select data-bind="options: AilmentsVM.AilmentsType(), optionsText: 'Name', value: SelectedAilment"></select></td>
</tr>
</script>
In the HTML template I need to bind AilmentsType to one of the columns as drop down. Can someone guide me how to achieve it? Thanks.
Your
AilmentsVMdoes not have global scope, because it is being created in your jQuery ready block, so you can’t access it directly in a data-bind.If you are using 1.3 beta, then you can use either the
$rootor$parentspecial variables that Knockout provides. In this case, they would be the same, as you are only one level in from the top-level scope. So, just do:$root.AilmentsType.If you are using an earlier version, then you can use the
templateOptionsfunctionality to pass options to a jQuery template. It would look like this:Then, access it like: