2012-09-24 111 views
2

你如何基於其他屬性進行條件綁定?Knockout.js條件綁定

例..

 
var ViewModel = { 
    IsAdded = ko.observable(), 
    AddedBy = ko.observable() 
} 

當我顯示出來..我不希望顯示AddedBy如果IsAddedBy爲空或假

事情是這樣的..

 
&ltinput type="text" data-bind="value: if (IsAdded != null && IsAdded) { AddedBy }"/> 

我知道這是不對的,但類似的...

+1

你想隱藏整個輸入框,還是隻是不填充它?如果您想完全隱藏它,請查看[Visible](http://knockoutjs.com/documentation/visible-binding.html)綁定。如果你不想填充它,那麼Tim的答案就是要走的路 –

回答

7

我會做的是這樣的;

var ViewModel = function() { 
    this.IsAdded = ko.observable('True'); 
    this.AddedBy = ko.observable('Test'); 
    this.AddedByText = ko.computed(function(){ 
     if (this.AddedBy() != null && this.IsAdded()) return this.AddedBy() 
     return ""; 
    }, this); 
} 

那麼你的投入將是

<input type="text" data-bind="value: AddedByText" /> 

這樣你保持你的包含範圍內的ViewModel從HTML分開的邏輯。

0

這個問題是舊的,但它可能會幫助別人尋找

<input type="text" data-bind="value: IsAdded ? AddedBy : "" "/> 

基本上如果IsAdded不爲空,然後設置value到AddedBy,別的什麼也不做