Knockout:访问 HTML 模板中的 viewmodel 实例
我有一个视图模型和关联的模板,如下所示。
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 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>
在 HTML 模板中,我需要将 AilmentsType 作为下拉列表绑定到其中一列。有人可以指导我如何实现它吗?谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
AilmentsVM
没有全局范围,因为它是在 jQuery 就绪块中创建的,因此您无法在数据绑定中直接访问它。如果您使用的是 1.3 beta,则可以使用 Knockout 提供的
$root
或$parent
特殊变量。在这种情况下,它们将是相同的,因为您仅距顶级范围一层。因此,只需执行:$root.AilmentsType
。如果您使用的是早期版本,则可以使用
templateOptions
功能将选项传递给 jQuery 模板。它看起来像这样:然后,像这样访问它:
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:Then, access it like: