最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Knockout.js conditional binding - Stack Overflow

programmeradmin1浏览0评论

How do you have conditional binding based on other properties?

Example..

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

When I display it.. I don't want to show AddedBy if IsAddedBy is null or false

Something like this..

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

I know that isn't right, but something like that...

How do you have conditional binding based on other properties?

Example..

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

When I display it.. I don't want to show AddedBy if IsAddedBy is null or false

Something like this..

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

I know that isn't right, but something like that...

Share Improve this question asked Sep 24, 2012 at 14:14 jaekiejaekie 2,3034 gold badges31 silver badges55 bronze badges 1
  • 1 Do you want to hide the whole input box, or just not populate it? If you want to hide it entirely, look at the Visible binding. If you don't want to populate it, then Tim's answer is the way to go – James Thorpe Commented Sep 24, 2012 at 14:40
Add a ment  | 

2 Answers 2

Reset to default 7

What I would do is this;

var ViewModel = function() {
    this.IsAdded = ko.observable('True');
    this.AddedBy = ko.observable('Test');
    this.AddedByText = ko.puted(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.

This question is old but it might help someone else looking

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

Basically if IsAdded is not null then set the value to AddedBy, else do nothing

发布评论

评论列表(0)

  1. 暂无评论