2013-01-10 129 views
1

選擇我定義我的選擇如下採用淘汰賽

<select id="selProductType" data-bind="options: productType , value: editProductType , optionsText: 'Name'" /> 

下面默認值是我的代碼,以填補選擇在我的視圖模型

// Loading combobox with Product Types 
    $.getJSON("../RestService/Product/AllProductTypes", 
     function (allData) { 
      var mappedProductType = $.map(allData, function (item) { 
       console.log(item.Id + ' ' + item.Name); 
       return new productType(item); 
      }); 
      self.productType(mappedProductType); 

     }); 

當我初始化頁面,我想設置默認值來選擇。所以我想下面

self.editProductType(4); 

但它給了我TypeErrror說對象4沒有方法Id。

如何去做。我也經歷了類似的帖子在stackoverflow,但沒有運氣。

Knockout JS binding initial/default value of dropdown (select) list

+0

你有一個額外的「中選擇元素 – phnkha

+0

是啊對不起,我刪除它 – DevelopmentIsMyPassion

回答

1

如果不指定:

optionsValue: 'Id' 
在數據綁定

,在這種情況下,結合值必須在productType數組的對象。

您可以選擇默認的對象:

self.editProductType(self.productType()[2]); 

什麼是optionsValue?

與optionsText類似,您還可以傳遞一個名爲optionsValue的附加參數來指定哪些對象的屬性應該用於設置KO生成的元素的value屬性。您也可以指定一個JavaScript函數來確定此值。該函數將接收所選項目作爲其唯一參數,並返回一個字符串用於元素的value屬性。

通常,您只想使用optionsValue作爲確保KO在更新可用選項集時能正確保留選擇的一種方法。例如,如果您通過Ajax調用反覆獲取「汽車」對象的列表,並且希望確保所選汽車被保留,則可能需要將optionsValue設置爲「carId」或每個「汽車」對象的任何唯一標識符否則KO不一定知道哪個以前的「汽車」物體對應於哪個新的物體。

閱讀更多:http://knockoutjs.com/documentation/options-binding.html

+0

我加optionsValue在我的數據綁定和寫如你所說 self.editProductType(self.productType() 4]); 但我得到錯誤「未捕獲的類型錯誤:無法調用方法'Id'未定義」 – DevelopmentIsMyPassion

+0

您必須確保self.productType是一個可觀察數組有超過4個項目,當您設置此 – phnkha

+0

self.productType是一個可觀察的數組,但是當你寫self.editProductType(self.productType()[2])時,我並沒有明白; 這是什麼值2.在我的選擇列表中會有4條記錄,我會將第4條記錄設置爲默認選擇 – DevelopmentIsMyPassion