[英]KnockoutJS: parameterize data-bind
我想為輸入元素上的數據綁定使用一個變量。 這是我嘗試過的:
<!-- ko foreach: [
{dataBind: {value: thing1}, txt: 'thing Name:'},
{dataBind: {maskedThing: thing2}, txt: 'thing Amount:'},
{dataBind: {value: thing3}, txt: 'thing3 Name:'}
] -->
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label class="control-label pull-left"><span data-bind="text: txt"></span></label>
<input type="text" class="form-control" data-bind="$data.dataBind">
</div>
</div>
</div>
<!-- /ko -->
txt: 變量有效:它用作 label。 但是,“$data.dataBind”的使用永遠不會被評估,它只是作為一個字符串保留。 如何以這種方式獲取要參數化的輸入元素的數據綁定? 謝謝。
根據我的經驗,我相信這是不可能的,你試圖實現它的方式。 要正確執行此操作,您可以創建一個自定義組件,以便您可以根據傳遞的對象/參數控制發生的情況
現在,為了讓它快速工作,您可以更改 html 並添加一個if
綁定來控制渲染的內容,以及對象上的標志,如下所示:
....
{dataBind: {value: thing1}, txt: 'thing Name:', isMasked: false},
{dataBind: {maskedThing: thing2}, txt: 'thing Amount:', isMasked: true},
{dataBind: {value: thing3}, txt: 'thing3 Name:', isMasked: false}
....
<input type="text" class="form-control" data-bind="if: isMasked, maskedThing: txt">
<input type="text" class="form-control" data-bind="ifnot: isMasked, value: txt">
在每次迭代中,任一輸入都將被渲染和綁定,具體取決於 object 的標志。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.