[英]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.