user2706
user2706

Reputation: 267

Multiple data-bind in knockout js

I have two text property data Date and City are observables. I need to concatenate two text property data in single div. and apply separate style for both the texts. Current Scenario is used knockoutjs data-bind property :

<div class="date" data-bind="text:Date" />
<div class="city" data-bind="text:City" />

Expected :

<div class="date city" data-bind=" text:Date text:City" />

Output : 2013-05-24 New York

Please guide me how to do this.

Upvotes: 21

Views: 32218

Answers (7)

Aishwarya Nagar
Aishwarya Nagar

Reputation: 111

You can simply write :-

data-bind = "text: Date() + City()" 

And if you want to add any string ex:- 2013-05-24 : New York , you can code as :

data-bind = "text: Date() + ':' + City()"

This way its worked for me.

Upvotes: 11

yoel neuman
yoel neuman

Reputation: 133

you could add 2 spans or call it like this

<div class="date" data-bind="text:Date() +' '+ city()" />

Upvotes: 3

Try using this format:

data-bind="text: city() + ', ' + state() + ' ' + zipcode()"

Upvotes: 0

Brian M. Hunt
Brian M. Hunt

Reputation: 83768

With ko.punches you could do

<div class='date city'>{{ Date() }} {{ City }}</div>

Just another option with a great plugin.

Upvotes: 1

Kamaraj G
Kamaraj G

Reputation: 11

use "," or "+" sign to do multiple data-bind.

<div class="date city" data-bind=" text:Date(), text: City" />


<div class="date city" data-bind=" text:Date() + City" />

Upvotes: 1

Nate
Nate

Reputation: 16888

To use separate styles for each part, you'll need separate HTML elements to attach those styles to. Using a span for each part would work.

<div>
    <span class="date" data-bind="text:Date"></span>
    <span class="city" data-bind="text:City" ></span>
</div>

Upvotes: 5

Joe Doyle
Joe Doyle

Reputation: 6383

You can't use two of the same binding on an element. Instead, you should create a computed which formats the text using the two values you want to display.

For example (Assuming your Date and City are observables):

viewModel.DateCity = ko.computed(function() {
  return viewModel.Date() + " - " + viewModel.City();
});

Then in your data-bind, you just bind to the computed.

<div class="date city" data-bind="text:DateCity" />

Another option is to combine the values in the binding directly.

<div class="date city" data-bind="text: Date() + ' - ' + City()" />

Personally I feel that the computed approach is a cleaner way to go.

Upvotes: 35

Related Questions