Reputation: 4809
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!
Upvotes: 48
Views: 25273
Reputation: 7332
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"}'/>
Upvotes: 1
Reputation: 710
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>
Upvotes: 0
Reputation: 16688
You just need to put double quotes around it:
<input data-bind='text: Title, attr: {"data-id": "Events[" + viewModel.events.indexOf($data) + "].Title"}'/>
Upvotes: 88