2

您如何基于其他属性进行条件绑定?

例子..

变量视图模型 = {
   IsAdded = ko.observable(),
   AdditionalBy = ko.observable()   
}

当我显示它时.. 如果 IsAddedBy 为 null 或 false,我不想显示 AdditionalBy

像这样的东西。。

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

我知道这是不对的,但类似的事情......

4

2 回答 2

7

What I would do is this;

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);
}

Then your input would be

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

This way you are keeping the logic contained within your ViewModel and separate from the HTML.

于 2012-09-24T14:33:28.510 回答
0

这个问题很旧,但它可能会帮助其他人寻找

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

基本上如果 IsAdded 不为空,则将其设置value为 AdditionalBy,否则什么也不做

于 2017-08-09T17:32:26.487 回答