dev.knockout
dev.knockout

Reputation: 399

knockoutjs: How to use boolean && in if condition?

I'm developing knockoutjs, I want to use boolean in data-bind and here my code but it is not working

<p class="cmt-post" data-bind="if:deleteDate&&owner='1'">
     <span data-bind="text:deleteDate">
     </span>
 </p>

Upvotes: 1

Views: 880

Answers (4)

abuduba
abuduba

Reputation: 5042

I would propose You to separate any logic to a viewModel instead

So consider method in your view model for example:

function ViewModel(){

  this.delete_date_visible = ko.pureComputed(
      this.getDeleteDateVisible,
      this
  )
};

ViewModel.prototype.getDeleteDateVisible = function(){
   return this.deleteDate() && this.owner == '1'
}

In the view:

<span data-bind="if: delete_date_visible">...</span>

or even

<!-- ko if: delete_date_visible -->
<span>...</span>
<!-- /ko -->

which looks cleaner i think.

The pure computed that is using view model's method because:

  • you don't need to call it in the template
  • the getter method could be re-used natively in the view model

Upvotes: 0

Wayne Ellery
Wayne Ellery

Reputation: 7958

If deleteDate and owner are observables you need to evaluate them using (). Also you should use === instead of = as === is used to compare equality and will also ensure that the types are the same. I.e. 1 === '1' will false whereas 1 == '1' is true.

<p class="cmt-post" data-bind="if:deleteDate()&&owner()==='1'">
     <span data-bind="text:deleteDate">
     </span>
</p>

Upvotes: 1

Mathew Thompson
Mathew Thompson

Reputation: 56449

You need double equals to compare equality (as you do in standard JS, otherwise it's an assignment):

 data-bind="if:deleteDate && owner == '1'">

Upvotes: 0

Rohan Kumar
Rohan Kumar

Reputation: 40639

You are assigning owner value use == instead of =

<p class="cmt-post" data-bind="if:deleteDate&&owner == '1'">
   <span data-bind="text:deleteDate"></span>

Upvotes: 0

Related Questions