当内部循环数组有多个字段时,嵌套的foreach循环

时间:2014-05-09 15:52:11

标签: jquery html knockout.js

如果children数组还有两个字段,则在以下示例中将对视图和viewmodel进行哪些更改 "儿童年龄"和"体重"。

视图:

 <h2>People</h2>
<ul data-bind="foreach: people">
<li>
    <div>
        <span data-bind="text: name"> </span> has <span data-bind='text: children().length'>&nbsp;</span> children:    
    </div>
    <ul data-bind="foreach: children">
        <li>
            <span data-bind="text: $data"> </span>                
        </li>
    </ul>
</li>

视图模型:

var Person = function(name, children) {
this.name = name;
this.children = ko.observableArray(children);

this.addChild = function() {
    this.children.push("New child");
}.bind(this);
 }

var viewModel = {
people: [
    new Person("Annabelle", ["Arnie", "Anders", "Apple"]),
    new Person("Bertie", ["Boutros-Boutros", "Brianna", "Barbie", "Bee-bop"]),
    new Person("Charles", ["Cayenne", "Cleopatra"])
    ],
};

ko.applyBindings(viewModel);

2 个答案:

答案 0 :(得分:1)

您可以通过使其成为一个对象数组而不仅仅是一个字符串数组,为children数组添加其他属性:

new Person("Annabelle", [
    {Name: "Arnie", weight: 25, age: 2}, 
    {Name: "Anders", weight: 45, age: 5}, 
    {Name: "Apple", weight: 29, age: 2}])

并且html改变如此:

<span data-bind="text: $data.Name"></span>    
<ul>
    <li data-bind="text: $data.weight +'lbs. '"/>
    <li data-bind="text: $data.age + ' years'"/>
</ul>

使用有效的解决方案查看此jsfiddle

答案 1 :(得分:1)

显然,孩子们需要成为对象。如果您希望它还包含这些属性,则可以重用Person

[{name:"Arnie", age: 1, weight: 2}]

然后绑定到属性:

<span data-bind="text: name"> </span> 
<span data-bind="text: age"> </span> 
<span data-bind="text: weight"> </span> 

此外,您可以使用foreach绑定的'as' aliasing功能,使HTML清晰地反映信息的来源

<ul data-bind="foreach: {data: children, as 'child'}">

子属性的绑定采用格式

<span data-bind="text: child.name"> </span> 

请参阅this fiddle以供参考。