1

我正在尝试使用“with”绑定在数组中显示后代元素。但它只显示“练习”中的最后一项,我想看到所有这些。怎么可能解决这个问题?在那之后,我怎样才能使数组中的每个项目都可编辑?

我的视图模型:

    function AppViewModel() {   
    var self = this;

    self.workouts = ko.observableArray([
        {name: "Workout1", exercises:{
            name: "Exercise1.1",
            name: "Exercise1.2",
            name: "Exercise1.3"
        }},
        {name: "Workout2", exercises:{
            name: "Exercise2.1",
            name: "Exercise2.2",
            name: "Exercise2.3"
        }},
        {name: "Workout3", exercises:{
            name: "Exercise3.1",
            name: "Exercise3.2",
            name: "Exercise3.3"
        }},        
        {name: "Workout4", exercises:{
            name: "Exercise3.1",
            name: "Exercise3.2",
            name: "Exercise3.3"
        }},        

]);

    self.removeWorkout = function() {
        self.workouts.remove(this);
    };
}

ko.applyBindings(new AppViewModel());

风景:

<div class="content">
    <ul data-bind="foreach: workouts">
        <li>
        <span data-bind="text: name"> </span>
         <a href="#" data-bind="click: $parent.removeWorkout">Remove</a>
         <ul data-bind="with: exercises">
            <li data-bind="text: name"></li>
         </ul>
        </li>
    </ul>   
</div>

这是 jsfiddle 的代码:http: //jsfiddle.net/9TrbE/

谢谢!

4

2 回答 2

5

您声明为对象的练习属性应该是一个数组。

self.workouts = ko.observableArray([
    {name: "Workout1", exercises:[
        { name: "Exercise1.1" },
        { name: "Exercise1.2" },
        { name: "Exercise1.3" }
    ]},
]);

所以你可以使用这个视图:

<div class="content">
    <ul data-bind="foreach: workouts">
        <li>
        <span data-bind="text: name"> </span>
         <a href="#" data-bind="click: $parent.removeWorkout">Remove</a>
         <ul data-bind="foreach: exercises">
            <li data-bind="text: name"></li>
         </ul>
        </li>
    </ul>   
</div>

声明:

var exercises = {
    name: "Exercise1.1",
    name: "Exercise1.2",
    name: "Exercise1.3"
};

就像这样做:

var exercises = {
    name: "Exercise1.1",
};
exercises.name: "Exercise1.2";
exercises.name: "Exercise1.3";
于 2013-10-22T13:37:57.130 回答
0

用这个得到它这是 jsfiddle 的这段代码

self.workouts = ko.observableArray([
    {name: "Workout1", exercises:[
        { name: "Exercise1.1" },
        { name: "Exercise1.2" },
        { name: "Exercise1.3" }
    ]},
]);

` http://jsfiddle.net/9TrbE/8/

于 2014-12-20T11:25:19.013 回答