2013-08-01 74 views
2

我有兩個下拉一個取決於其他(級聯)。 'MainCategories'上的選擇決定'SubCategories'的項目。 另外,'MainCategories'上的選擇也決定了表格行的可見性。 以下是我的嘗試:淘汰賽級聯下拉

<table> 
    <tbody data-bind="foreach: contacts"> 
     <tr> 
      <td>MainCategories: 
       <select data-bind='options: MyCategories, value: mycategory, optionsText: "Type", optionsValue: "Type",optionsCaption: "Select..."'></select> 
      </td> 
      <td> 
       <!-- ko with: mycategory -->SubCategories: 
       <select data-bind='options: Categories, optionsText: "Category", optionsCaption: "Select...", value: $parent.product'></select> 
       <!-- /ko --> 
      </td> 
     </tr> 
     <tr data-bind="visible:mycategory()=='Type1'"> 
      <td>I am visible</td> 
     </tr> 
    </tbody> 
</table> 

<script type = "text/javascript" > 
    var MyCategories = [{ 
     "Categories": [{ 
      "Category": "Category1" 
     }, { 
      "Category": "Category2" 
     }], 
     "Type": "Type1" 
    }, { 
     "Categories": [{ 
      "Category": "Category3" 
     }, { 
      "Category": "Category4" 
     }], 
     "Type": "Type2" 
    }]; 
    var initialData = [{ 
     category: "Mobile", 
     product: "Nokia" 
    }]; 

    var ContactsModel = function (contacts) { 
     var self = this; 
     self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (contact) { 
      return { 
       mycategory: ko.observable(contact.category), 
       product: ko.observable(contact.product) 
      }; 
     })); 

    }; 

    ko.applyBindings(new ContactsModel(initialData)); 
</script> 

如果我刪除optionsValue:「類型」,則「子類別」得到正確的項目。但是表格行的可見性並未按預期工作。 如果我有optionsValue:「Type」,那麼'SubCategories'沒有被填充。而且,當我更改'MainCategories'的選項1或2次時,只有可視性工作正常。

請幫我看看我在這裏做錯了什麼。 謝謝,

回答

2

我讀了你的問題,我有一種感覺,這會回答它,如果不解決這個問題,以至於你可以應用它 -

* 問題* -

你需要有使用Knockout級聯下拉列表選擇一個值並將您的可觀察值設置爲等於子選擇的選定對象。

* 解決方案* -

使用計算,以使第二個下拉依賴於第一。示例 -

var selectedParent = ko.observable(); 

var parentCategories = ko.observableArray(MyCategories); 

var childCategories = ko.computed(function() { 
    if (!selectedParent()) { return new Array(); } 
    var childArray = []; 
    // get the values you want for the child here 
    return childArray; 
}); 

通過添加if(!selectedParent())您正在使childCategories依賴於selectedParent。每當選擇更改時,childCategories將自動更新。

然後你的視圖可以是這樣的 -

<td>MainCategories: 
       <select data-bind='options: parentCategories, value: selectedParent, optionsText: "Type", optionsValue: "Type",optionsCaption: "Select..."'></select> 
      </td> 
      <td> SubCategories: 
       <select data-bind='options: childCategories, optionsText: "Category", optionsCaption: "Select...", value: $parent.product'></select> 
       <!-- /ko --> 
      </td>