Working with knockoutjs attr to write data* attributes
Asked Answered
C

3

47

I'm running into a problem with data* attributes in knockout.js ie. writing them out with attr.

I can do this without a problem:

<input data-bind='text: Title, attr: {name: "Events[" + viewModel.events.indexOf($data) + "].Title"}'/>

but if I want to use data-id, the regular way doesn't work so I put a single quote around the attribute:

<input data-bind='text: Title, attr: {'data-id': "Events[" + viewModel.events.indexOf($data) + "].Title"}'/>

which gives me

Error: Unable to parse bindings.
Message: SyntaxError: missing } in compound statement;
Bindings value: attr: {
http://127.0.0.1:21254/Scripts/knockout/knockout-2.2.0.js

can someone see what went wrong here?

Cheers!

Catechize answered 23/1, 2013 at 1:26 Comment(0)
S
88

You just need to put double quotes around it:

<input data-bind='text: Title, attr: {"data-id": "Events[" + viewModel.events.indexOf($data) + "].Title"}'/>
Strife answered 23/1, 2013 at 2:4 Comment(1)
@Michael Best: Thanks, you helped me solve a related problem.Ethics
G
0

Below is a working snippet illustrating how to set a custom data attribute value with Knockout:

ko.applyBindings({
  somevalue: 'foo',
  title: 'Knockout custom data attribute binding --  example'
});

$("#result").text($("#test-el").data("someattr"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div data-bind="text: title, attr: {'data-someattr': somevalue}" id="test-el"></div>

<p>
  <b>Test data attribute expected value:</b> foo
</p>

<p>
  <b>Test data attribute value: </b>
  <span id="result"></span>
</p>
Girl answered 3/2, 2016 at 19:7 Comment(0)
F
0

You don't even need to put either double or single quotes around attr name, just go with simply data-id

<input data-bind='text: Title, attr: {data-id: "Events[" + viewModel.events.indexOf($data) + "].Title"}'/>
Fidelafidelas answered 13/10, 2017 at 6:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.