bsod_
bsod_

Reputation: 941

Knockout foreach within foreach

Take for instance -

   <!--ko foreach: WorkItems-->
      <tbody data-bind="foreach: ActionPlans">
         // table data here
      </tbody>
   <!--/ko-->

I am trying to show within "table data here" only ActionPlan items that belong to the current iterated WorkItem.

Issue -

My problem is that currently "table data here" shows all ActionPlans for all WorkItems.

My model is structured as Person > WorkItem(array) > ActionPlan(array)

I have tried

   <!--ko foreach: WorkItems-->
      <tbody data-bind="foreach: $parent.ActionPlans">
         // table data here
      </tbody>
   <!--/ko-->

Adding the $parent does not show any ActionPlans...

-------------- Edit as requested - -------------------

var PersonViewModel = function(data) {
var self = this;
ko.mapping.fromJS(data, trainingCourseItemMapping, self);

self.addWorkItem = function() {
    var WorkItem = new WorkItemVM({
        Id: null,
        JobSkillsAndExpDdl: "",
        JobSkillsAndExperience: "",
        ActionPlans: ko.observableArray(),
        PersonId: data.Id
        })
   self.WorkItems.push(WorkItem)
};

self.addActionPlan = function () {
    var actionPlan = new ActionPlanVM({
        Id: null,
        priorityAreaStage: "",
        goal: "",
        action: "",
        byWho: "",
        byWhen: ""
        WorkItemId: data.Id
    });
    self.ActionPlans.push(actionPlan);
};
}

Array mapping

var trainingCourseItemMapping = {
'WorkItem': {
    key: function(workitem) {
        return ko.utils.unwrapObservable(workitem.Id);
    },
    create: function(options) {
        return new WorkItemVM(options.data);
    },
    'ActionPlans': {
        key: function (actionPlanItem) {
            return ko.utils.unwrapObservable(actionPlanItem.id);
        },
        create: function (options) {
            return new ActionPlanVM(options.data);
        }

    }
}

Array item mapping

var WorkItemVM = function(data) {
    var self = this;
    ko.mapping.fromJS(data, trainingCourseItemMapping, self);
}

var ActionPlanVM = function(data) {
    var self = this;
    ko.mapping.fromJS(data, {}, self);
}

EDIT 2 ---------------------

Here is the rendered HTML as you can see it renders a foreach: ActionPlans for every WorkItem with an ActionPlan

enter image description here

Upvotes: 0

Views: 125

Answers (1)

gkb
gkb

Reputation: 1459

I don't think you should need to include $parent as it is already inside of the WorkItems binding context.

Fiddle

Upvotes: 1

Related Questions