Working with knockoutjs attr to write data* attributes

MikeW picture MikeW · Jan 23, 2013 · Viewed 21.5k times · Source

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!

Answer

Michael Best picture Michael Best · Jan 23, 2013

You just need to put double quotes around it:

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