我如何在knockoutjs中进行嵌套循环

时间:2014-03-27 13:52:45

标签: knockout.js

你好我在循环中尝试使用knockout.js绑定循环,但是遇到了麻烦。

我的视图模型

<script>
function Category(data) {
    this.id = ko.observable(data.Id);
    this.Name = ko.observable(data.Name);
    this.Products = ko.observableArray
    ([{
        id: ko.observable(data.Products.Id), Name: ko.observable(data.Products.Name),
    }]);
}
function CatListViewModel() {
    var self = this;
    self.Category = ko.observableArray([]);
    Category.Products = ko.observableArray([]);
    $.getJSON("/Home/Get", function (allData) {
        var mappedCats = $.map(allData, function (item) { return new Category(item); });
        self.Category(mappedCats);
        console.log(allData);
        console.log(mappedCats);
    });
}
ko.applyBindings(new CatListViewModel());

Html元素

<ul data-bind='foreach:Category'>
    <li><span data-bind='text:Name'></span>
        <ul data-bind='foreach:Category.Products'>
            <li data-bind='text:Name'></li>
        </ul>
    </li>
</ul>

服务器端模型

        public JsonResult Get()
    {
        var catList = new List<Category>();

        for (int i = 0; i < 20; i++)
        {
            var procList = new List<Product>();
            var Cat = new Category()
            {
                Id = i.ToString(),
                Name = "Category " + i,
            };
            for (int j = 0; j < 20; j++)
            {
                var prod = new Product()
                {
                    Id = j.ToString(),
                    Name = i + " Cats " + j + " Prod",
                    Price = i + j.ToString(),

                };
                procList.Add(prod);
            }
            Cat.Products = procList;
            catList.Add(Cat);
        }
        return Json(catList, JsonRequestBehavior.AllowGet);
    }

Html输出

<ul data-bind="foreach:Category">
    <li><span data-bind="text:Name">Category 0</span>
        <ul data-bind="foreach:Category.Products"></ul>
    </li>

    <li><span data-bind="text:Name">Category 1</span>
        <ul data-bind="foreach:Category.Products"></ul>
    </li>

    <li><span data-bind="text:Name">Category 2</span>
        <ul data-bind="foreach:Category.Products"></ul>
    </li>   

   ... More item
</ul>

外部循环正确呈现,但我从内部循环中得不到任何内容,甚至没有错误消息。

1 个答案:

答案 0 :(得分:1)

您的HTML不适合我,删除Category.块中的Products,因为它默认会引用每个父Category

<!-- Loop over each Category -->
<ul data-bind="foreach:Category">
    <li>
        <span data-bind="text:Name"></span>
        <!-- Loop over each Product in the current category -->
        <ul data-bind="foreach:Products">                
            <li>
                <span data-bind="text:Name"></span>
            </li>
        </ul>
    </li>
</ul>

如果这不起作用,请使用$data专门引用父Category属性:foreach:$data.Products