繁体   English   中英

如何在空容器knockoutjs的html绑定中显示observable

[英]How to display observable in html binding with empty container knockoutjs

我有一个这样的数组,我试图绑定选择。

var arr =       [{
    "Id": 1,
    "Rate": 5,
    "Price": 200,
    "Name": "History",
    "template": "<option id='1'>History</option>"
}, {
    "Id": 2,
    "Rate": 5,
    "Price": 150,
    "Name": "Geographic",
    "template": "<option id='2'>Geographic</option>"
}, {
    "Id": 3,
    "Rate": 1,
    "Price": 75,
    "Name": "Maths",
    "template": "<option id='3'>Maths</option>"
}, {
    "Id": 4,
    "Rate": 2,
    "Price": 50,
    "Name": "Statistics",
    "template": "<option id='4'>Statistics</option>"
}, {
    "Id": 5,
    "Rate": 3,
    "Price": 120,
    "Name": "Drawing",
    "template": "<option id='5'>Drawing</option>"
}]

如您所见,有一个模板,其中包含一个选项字符串。 这是我用一些功能创建的。 现在我想绑定这个数组来选择。

self.Result = ko.observableArray(arr)

视图

<select data-bind="foreach:Result">
    <!--  ko html:$data.template -->
    <!--  /ko -->
</select>

现在它产生了一个错误。 html绑定不能与虚拟元素一起使用。

如果我试试这个

ko.virtualElements.allowedBindings.html = true;

它没有解决问题,因为我认为它只适用于自定义绑定。

这有什么解决方案吗? 如果我需要处理此事,我该怎么办?

解决方案是直接在select元素上使用html绑定并手动将模板连接到一个字符串:

<select data-bind="html: Result.map(function(i) { return i.template }).join('\n')">

</select>

演示JSFiddle

但是,如果你可以,那么你应该改变你的设计而不是发回模板html,而是在客户端上构建它:

<select data-bind="foreach:Result">
    <option data-bind="attr: {id: Id}, text: Name"></option>
</select>

演示JSFiddle

感谢@nemesv提供的解决方案,我来到了这一点

self.LoadTemplate = function(){
    return self.Result().map(function(i) { return i.template }).join('\n')
}

<select data-bind="html:LoadTemplate()"></select>

我仍然希望html绑定支持虚拟元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM