user3378165
user3378165

Reputation: 6916

Adding condition to data-bind="with"

I have a Users table, each user is clickable, once you click on it- a modal popups with the user's information.

the div of the modal:

<div class="infoForm" data-bind="with: $root.selectedItem">
      <input id="companyName" placeholder="Company Name" data-bind="value: name" />
      <div class="cont">
      <label for="address">ADDRESS</label>
      <input class="contField" placeholder="Address 1" id="address" data-bind="value: address1" />
      <input class="contField" placeholder="Address 2" id="address2" data-bind="value: address2" />
      <input class="contField" id="city" placeholder="City" data-bind="value: city" />
      <input class="contField" id="state" placeholder="State" data-bind="value: state" />
      <input class="contField" id="zip" placeholder="Zip" data-bind="value: zip" />
...
</div>

The problem is that if selectedItem is empty, the modal popups blank, without any content.

I wanted to add a condition to the data-bind to happen only if $root.selectedItem is not null becasue when I take out the data-bind at all it does work.

I tried that:

<div class="infoForm" data-bind="with: $root.selectedItem ? $root.selectedItem : ''">
    .....
</div>

But it doesn't work, it just doesn't happen, in other types of binding (text, value it does work).

The selectedItem is being set when one of the users on the table is being clicked:

 <td class="name n" data-bind="text: name, click: $root.setSelectedItems.bind($data)"></td>

The View Model:

var UsersViewModel = function () {
    var self = this;
    self.selectedItem = ko.observable();
    ...

    self.setSelectedItems = function (selectedUser) {
    if (selectedUser) {
        self.selectedItem(selectedUser);
    }
}
}

Any idea on how to achieve that?

Upvotes: 0

Views: 47

Answers (1)

user3378165
user3378165

Reputation: 6916

I solve it by setting the selectedItem with an empty user:

self.selectedItem = ko.observable(new User(""));

Upvotes: 1

Related Questions