具有添加/删除功能的knockout.js中的动态模板控件

时间:2013-06-18 14:28:25

标签: templates dynamic knockout.js

如果我解释这个分裂,那就更好了。 第一个:我必须添加和删除一行控件(它正在工作) 第二个:根据控件中的选定选项,我必须显示不同的选项或控件。 (它也适用于模板)。

问题是让两者协同工作。每次我添加一行,然后选择一个选项,然后显示选项/控制/文本,然后也能删除该行。

提前致谢。

HTML:

<table data-bind="foreach: fLines">
    <tr>
        <td>
            <select data-bind="options: formatValues, value: type"></select>
        </td>
        <td data-bind="template: type"></td>
        <td>
            <a href="#" data-bind='click: $parent.removefLine'>Remove</a>
        </td> 
    </tr>
</table>
<button style="background-color: transparent; border: none;" data-bind="click: addfLine()">Add Format</button>

<script id="A" type="text/html">
    <input data-bind="value: value1" /> 
</script>

<script id="B" type="text/html">
    <span>removes leading and trailing spaces</span>
</script>

<script id="C" type="text/html">
</script>

KO:

var formatValues = ["A", "B", "C"];

var Item = function(format) {
    var self = this;
    self.type = ko.observable(format);
    self.value1 = ko.observable();
};

var Formatters = {
    fLines: [ new Item("C") ],
    addfLine: function(){fLines.push(new Item("C"))}
};


ko.applyBindings(Formatters);

1 个答案:

答案 0 :(得分:0)

你快到了。 'formatValues'需要成为参与数据绑定的viewmodel的一部分。

<select data-bind="options: $root.formatValues, value: type"></select>

JSFiddle with add/remove