嵌套的Foreach循环与knockoutjs中的不同列表

时间:2017-03-21 09:49:50

标签: jquery arrays list knockout.js

我先列出两个列表 SelectedServiceSubCategoryList 声明为

self.SelectedServiceSubCategoryList = ko.observableArray([]);

和第二个 ServiceCategoryList

声明为

self.ServiceCategoryList = ko.observableArray([]);

这些列表的模型如下 for SelectedServiceSubCategoryList

    function SSCategoryViewModel(obj) 
{
                var x = this;
                x.Id = obj.SCategory.Id;
                x.SC_Name = obj.SCategory.SC_Name;
                x.SSC_Id = obj.SSC_Id;
                x.SSC_Name = obj.SSC_Name;
                x.Value = ko.observable(0);
                x.IsSelected = ko.observable(false);
                x.CompanyID = self.Company.CompanyID();
                x.Value.subscribe(function (newValue) {
                    self.IsEditingServices(true);
                    self.DrawServiceGraph(x);
                    $('#serviceIndustries .editButtonIocn .edit').click();
                });
                x.OnClickSlider = null;
            }

和 for ServiceCategoryList

function SCategoryViewModel(obj) 
{
                var x = this;
                x.Id = obj.Id;
                x.SC_Name = obj.SC_Name;
                x.IsSelected = ko.observable(false);
                x.CompanyID = self.Company.CompanyID();
                x.SSC_List = ko.observableArray([]);
                x.IsValueChanged = ko.computed(function () {
                    var selectedList = ko.utils.arrayFilter(x.SSC_List(), function (o) { return o.IsSelected() && o.Value() > 0; });
                    if (selectedList.length > 0) { return true; }
                    else { return false; }
                }, x);
            }

我正在使用HTML中的data-bind属性来使用foreach绑定SelectedServiceSubCategoryList

<ul class="collapsible popout" data-collapsible="accordion"
                        data-bind="foreach:SelectedServiceSubCategoryList">

我想在 SelectedServiceSubCategoryList foreach循环

中绑定 ServiceCategoryList

如何建立这两个列表之间的关系。

1 个答案:

答案 0 :(得分:0)

如果两者都声明在同一级别,如下所示:

var viewModel = function() {
  ...
  self.SelectedServiceSubCategoryList = ko.observableArray([]);
  ...
  self.ServiceCategoryList = ko.observableArray([]);
  ...
}

然后调用$parent来访问ServiceCategoryList。

<ul class="collapsible popout" data-collapsible="accordion" data-bind="foreach: SelectedServiceSubCategoryList">
  <li>
    <ul data-bind="foreach: $parent.ServiceCategoryList ">
      ...
    </ul>
  </li>
  ...
</ul>