Reputation: 4015
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.
Upvotes: 0
Views: 1507
Reputation: 114792
Your AilmentsVM
does 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 $root
or $parent
special 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 templateOptions
functionality to pass options to a jQuery template. It would look like this:
<tbody data-bind='template: { name: "ailmentRowTemplate", foreach: Ailments, templateOptions: { types: AilmentsType } }'>
</tbody>
Then, access it like:
<select data-bind="options: $item.types, optionsText: 'Name', value: SelectedAilment"></select>
Upvotes: 1