0

我是 KnockoutJS 新手。

我在下面写了一个视图,在运行时看不到每个类别的 categoryVariables。你能看看这里有什么问题吗?

谢谢你的帮助。

我的代码视图:

<table class="table">
    <thead>
    </thead>
    <tbody data-bind="foreach: categories">
        <tr>
            <td data-bind="text: Name">
                <table>
                    <tbody data-bind="foreach: categoryVariables">
                        <tr>
                            <td data-bind="text: Name"></td>
                        </tr>
                    </tbody>
                </table>
            </td>
            <td><button data-bind='click: $root.addCategoryVariable'>Add a category variable</button></td>
        </tr>
    </tbody>
</table>

<button data-bind='click: addCategory'>Add a category</button>

<script type="text/javascript">

    var resumeDataViewModel;

    function Category(data) {
        var self = this;

        self.ID = data.ID;
        self.Name = data.Name;

        self.categoryVariables = ko.observableArray([
            new CategoryVariable({ID: '1', Name: 'asd'})
        ]);
    }

    function CategoryVariable(data) {
        var self = this;

        self.ID = data.ID;
        self.Name = data.Name;
    }

    function ResumeDataViewModel() {
        var self = this;

        self.categories = ko.observableArray([
            new Category({ID: '1', Name : 'Contact', Category: {ID: '1', Name: 'gfdg'}}),
            new Category({ID: '2', Name : 'Education', Category: {ID: '2', Name: 'asdasd'}})
        ]);

        self.addCategory = function(){
            self.categories.push(new Category({
                Name: "sa d"
            }));
        }

        self.addCategoryVariable = function (category) {
            category.categoryVariables.push(new CategoryVariable({
                Name: 'asd'
            }));
        }
    }

    ko.applyBindings(resumeDataViewModel = new ResumeDataViewModel());
</script>

正在寻找您的回复。非常感谢。

4

1 回答 1

3

您的问题在于 text: Name 的绑定,然后将表格添加到同一个 td. 我已将 categoryVariables 的表移至单独的 TD,它工作正常。

由于您已经绑定了 TD 的文本,Ko 的数据绑定将覆盖您在其中的任何其他内容,并且只需从 observable 中设置文本。如果您正在查看不同的 UI 布局,请相应地更改您的 HTML,但请记住以上内容。

还要在 KO 文档中查看有关使用无容器绑定和 with 绑定的信息。这些可以帮助您创建更好的 HTML 布局。

检查这个小提琴:http: //jsfiddle.net/7BNQy/

修改后的 HTML:

<table class="table">
<thead>
</thead>
<tbody data-bind="foreach: categories">
    <tr>
        <td data-bind="text: Name">

        </td>
        <td>
            <table>
                <tbody data-bind="foreach: categoryVariables">
                    <tr>
                        <td data-bind="text: Name"></td>
                    </tr>
                </tbody>
        </table></td>
        <td><button data-bind='click: $root.addCategoryVariable'>Add a category variable</button></td>
    </tr>
</tbody>
</table>

<button data-bind='click: addCategory'>Add a category</button>
于 2012-12-18T10:17:30.733 回答