Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the id attribute with knockoutjs including a prefix

I'm using KnockoutJS to iterate over an object, like this:

Now this all works. But the problem i have is that it sets the id of the button to just a number. So it looks like this:

<button id="1">Button 1</button> <button id="3">Button 2</button> <button id="8">Button 3</button> 

So i tried to put a prefix in front of the the 'Id' property, like so:

<div data-bind="foreach:Items">     <button data-bind="text: Name, attr: {'id': 'myprefix_' + Id}"></button> </div> 

But that doesn't seem to be working. My id gets filled with some Knockout observable function when i do it like that...

So my question is, how can i add a prefix when i specify the id attribute of a field?

like image 844
w00 Avatar asked Sep 20 '12 08:09

w00


People also ask

How do you activate a Knockoutjs model?

To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.

What is $data in knockout?

The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.


2 Answers

Actually used this today - to unwrap the observable I had to do:

<button data-bind="attr: { id: 'prefix_' + $index() }"> Send </button> 

Hope this helps.

like image 85
Cordell Lawrence Avatar answered Sep 21 '22 03:09

Cordell Lawrence


If Id is an observable, you must "unwrap" it: 'myprefix_' + Id().

like image 40
Michael Best Avatar answered Sep 21 '22 03:09

Michael Best