javascript - Knockout.js conditional binding - Stack Overflow

How do you have conditional binding based on other properties?Example..var ViewModel = {IsAdded = ko.ob

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744703894a4588938.html

相关推荐

  • javascript - Knockout.js conditional binding - Stack Overflow

    How do you have conditional binding based on other properties?Example..var ViewModel = {IsAdded = ko.ob

    1天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信