103

I need to have multiple data bindings on one element. For example, I want a href as well as a html data-binding on one a tag. I have tried this,

<a data-bind="html: name" 
   data-bind="attr: { href: url }" 
   data-bind="attr: { 'data-prop': xyz }">
</a>

But this doesn't work. It seems knockout only supports binding one data-bind property? How to bind both the href, the inner html, and a custom "data-prop" attribute on one element?

Jeroen
  • 60,696
  • 40
  • 206
  • 339
Imran Qadir Baksh - Baloch
  • 32,612
  • 68
  • 179
  • 322

5 Answers5

141

Like this:

<a data-bind="html: name, attr: { href: url }">

You use comma-separated bindings - the attribute is the same as passing an object:

{
    html: name, 
    attr: { href: url }
}

Or, if you're asking about multiple attr bindings at once:

<a data-bind="html: name, attr: { href: url, 'data-prop': FullName }">
Jeroen
  • 60,696
  • 40
  • 206
  • 339
paulslater19
  • 5,869
  • 1
  • 28
  • 25
  • Can you also tell me that, if viewModel.tasks = ko.observableArray(tsks) then changing viewModel.tasks = [new Array], How to tell knock that array is changed – Imran Qadir Baksh - Baloch May 22 '12 at 10:35
  • when setting a ko.observable value, try doing it like this: `viewModel.tasks([1,2,3]);`. I.e. you call it as a function, passing the new value as a parameter – paulslater19 May 22 '12 at 10:38
3

This is how I implemented the source attribute and click event using data-bind. You may find it useful.

<img data-bind="{click: function(data, event) {ESVendorWidget.loadFunction(data,event)},
                 attr: {src: $data.Photo.PhotoUrl }}"
     alt="package pic" class="big" />
serv-inc
  • 35,772
  • 9
  • 166
  • 188
aamir sajjad
  • 3,019
  • 1
  • 27
  • 26
2

I simply use:

<input type="checkbox"
    data-bind="click: callFunction(), checkedValue: 0, checked: Card.Days">

for a checkbox element.

chris
  • 4,827
  • 6
  • 35
  • 53
2

you can use multiple properties using , like below

<a data-bind="attr: { href: url, id: id , class: classvalue}">

object like this

{ url: 'http://stackoverflow.com', id:'newid' , classvalue: 'classname' }
serv-inc
  • 35,772
  • 9
  • 166
  • 188
Surendra Kumar Ahir
  • 1,609
  • 18
  • 19
1

you can use like below

data-bind="text: method.method_title, attr: {'id': 'label_method_' + method.method_code}"

Gohil Rajesh
  • 113
  • 8
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Also, you should check how to format your posts properly here https://stackoverflow.com/editing-help#code – nima Sep 23 '21 at 09:35