2017-06-18 145 views
0

我有這個select設置默認值,如果沒有值

<select data-bind="options: $root.users(), optionsText: 'name', optionsValue: 'id', value: $root.selectedUser, optionsCaption: 'Select one'"></select> 

我只需要如果$root.selectedUser = 0否則我不需要的默認值要選擇的默認值(「選擇一個」)。

我試過:

<select data-bind="options: $root.users(), optionsText: 'name', optionsValue: 'id', value: $root.selectedUser, optionsCaption: $root.selectedUser() === 0 ? 'Select one' : ''"></select> 

但它不工作。 (如果$root.selectedUser = 0它顯示列表的第一個值而不是默認值。)

有關如何實現該目標的任何想法?

+1

我無法重現您的錯誤:http://jsfiddle.net/ogLpxc0L/1/。你能更新小提琴嗎? –

+0

@JoseLuis謝謝,我發現是什麼原因導致了這個問題:'selectedUser'無法獲得'0'值,當我將它設置爲'0'值時,它會得到'undefined'。爲什麼'selectedUser'不能是'0'?我添加了一個'console.log()到小提琴。 – user3378165

+0

在小提琴的更新(http://jsfiddle.net/ogLpxc0L/4/)中,您可以選擇'0'。我添加了一行「Selected」,以顯示所選的實際值。另外,我將第一個用戶更改爲id = 0。在此鏈接(http://knockoutjs.com/documentation/options-binding.html)中,它表示「未定義」值顯示默認選項。 –

回答

1

如果這個模型視圖:

var User = function(id, name) { 
     this.name = name; 
     this.id = id; 
    }; 

    var viewModel = { 
     users : ko.observableArray([ 
      new User(0,"User 1"), 
      new User(2,"User 2"), 
      new User(3,"User 3") 
     ]), 
     selectedUser : ko.observable(0) 
    }; 


    ko.applyBindings(viewModel); 

我有了ID爲0

如果您在觀察到的是一個ID的任何值保存用戶,它會選擇此選項。所有這一切都將選擇一個選項:

selectedUser : ko.observable(0) 
selectedUser : ko.observable(2) 
selectedUser : ko.observable(3) 

如果保存的任何值,或undefined,則默認選項顯示。

這個fiddle顯示這個例子。

+1

謝謝你的回答! – user3378165

+0

很高興幫助! :-) –