-1

In case I do:

data-bind="attr: {'id': $index}"

than IDs are 0, 1, 2... but if I do:

data-bind="attr: {'id': $index>0 ? 'choice'+$index : 'choice'}"

than ID is always 'choice', what do I do wrong?

It is Knockout v3.4.2

skobaljic
  • 9,379
  • 1
  • 25
  • 51
  • Possible duplicate of [knockout.js using $index with if binding](https://stackoverflow.com/questions/11318441/knockout-js-using-index-with-if-binding), https://stackoverflow.com/questions/11302338/knockout-is-not-evaluating-an-expression-when-using-index-in-a-binding, https://stackoverflow.com/questions/17734415/index1-in-knockout-foreach-binding – Jeff Mercado Aug 23 '17 at 08:14
  • It is a duplicate, but from my perspective didn't know what to search for, thought the condition syntax could be wrong. – skobaljic Aug 23 '17 at 08:18

1 Answers1

2

$index is actually an observable. In a simple binding, knockout will handle it automatically. In a more complex expression, it doesn't, you need to manually call it:

data-bind="attr: {'id': $index()>0 ? 'choice'+$index() : 'choice'}"

They all end up with just 'choice', because $index>0 will always evaluate to false, since it's comparing the text representation of the $index observable function with 0. This function starts with f and "f" > 0 is false.

James Thorpe
  • 31,411
  • 5
  • 72
  • 93
  • Yes, that makes sense and it works. But I have never found docs about 'simple' and 'complex' binding, always had problems with that :( – skobaljic Aug 23 '17 at 08:15
  • @skobaljic Just think of anything other than an observable by itself (as per your first example) as "complex". – James Thorpe Aug 23 '17 at 08:16
  • I get it, no problems, but never find explanation in docs, was something I had to figure myself. Is there any docs about it? Something that says: If you bind observable only, than you need no brackets? – skobaljic Aug 23 '17 at 08:19