3

Concider a jQuery Mobile "list" containing a radio button and a label for it.

<!-- ko foreach: $data.answers -->
<input type="radio" name="radio-choice" data-bind="attr: { id: [...] }" />
<label data-bind="attr:{ for: [...] }">Label</label>
<!-- /ko -->

In order to work, the for attribute of the label needs to be the same as the id of the input.

REPLACEMENT FOR [...]            RESULTS IN
$index                           ok
'radio-nr-'+$index               fails
$root.testFunction(1)            ok
$root.testFunction($index)       fails
'radio-nr-'.concat(1)            ok
'radio-nr-'.concat($index)       fails

where

function testFunction(a) {  return "radio-nr-"+a; };

Why do all my attempts of concatenating the $index fail?

Thanks!

Cotten
  • 8,787
  • 17
  • 61
  • 98
  • duplicate of http://stackoverflow.com/questions/11302338/knockout-is-not-evaluating-an-expression-when-using-index-in-a-binding – Michael Best Oct 02 '12 at 09:54

1 Answers1

9

From the $index documentation:

Unlike the other binding context properties, $index is an observable

So you need to write $index() (note the parenthesis) in your binding:

<!-- ko foreach: $data.answers -->
<input type="radio" name="radio-choice" 
                    data-bind="attr: { id: 'radio-nr-' + $index()  }" />
<label data-bind="attr:{ for: 'radio-nr-' + $index() }">Label</label>
<!-- /ko -->

A working sample in JSFiddle

nemesv
  • 138,284
  • 16
  • 416
  • 359