[英]How to display observable in html binding with empty container knockoutjs
I have an array like this which i am trying to bind with a select. 我有一个这样的数组,我试图绑定选择。
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>"
}]
As you can see there is template which contains a string for option. 如您所见,有一个模板,其中包含一个选项字符串。 This i have created with some function. 这是我用一些功能创建的。 Now i want to bind this array to select. 现在我想绑定这个数组来选择。
self.Result = ko.observableArray(arr)
View 视图
<select data-bind="foreach:Result">
<!-- ko html:$data.template -->
<!-- /ko -->
</select>
And now it produces an error. 现在它产生了一个错误。 html binding can not be used with virtual elements. html绑定不能与虚拟元素一起使用。
Moreover if i try this 如果我试试这个
ko.virtualElements.allowedBindings.html = true;
It does not solve the problem as i assume it is only for custom bindings. 它没有解决问题,因为我认为它只适用于自定义绑定。
Is there any solution for this? 这有什么解决方案吗? What should i do if i need to procees with this 如果我需要处理此事,我该怎么办?
On solution would be to directly use the html
binding on the select
element and manually concatenate your template to one string: 解决方案是直接在select
元素上使用html
绑定并手动将模板连接到一个字符串:
<select data-bind="html: Result.map(function(i) { return i.template }).join('\n')">
</select>
However if you could then you should change your design and not send back the template html but build it on the client: 但是,如果你可以,那么你应该改变你的设计而不是发回模板html,而是在客户端上构建它:
<select data-bind="foreach:Result">
<option data-bind="attr: {id: Id}, text: Name"></option>
</select>
Thanks for the solution @nemesv provided i came to this point 感谢@nemesv提供的解决方案,我来到了这一点
self.LoadTemplate = function(){
return self.Result().map(function(i) { return i.template }).join('\n')
}
And 和
<select data-bind="html:LoadTemplate()"></select>
Still i would like html binding to support virtual elements. 我仍然希望html绑定支持虚拟元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.