72

If I want to bind a template to a plain old array of strings, what do I put in the ${??} expression?

I hope this snippet isn't too short so as to confuse:

<ul data-bind="template: { name: 'authorTemplate', foreach: authors }">
</ul>

where authors is simply ["a", "b", "c"]

<script type="text/x-jquery-tmpl" id="authorTemplate">
    <li>${what_do_I_put_here???}</li>
</script>

I've tried: val value this and this.toString(). The last two displayed [object Object] so I suspect I'm pretty close there.

Robert Brooker
  • 2,148
  • 24
  • 22
Adam Rackis
  • 82,527
  • 56
  • 270
  • 393

2 Answers2

107

From the documentation, the answer is:

When using a template: ${$data}

When not using a template: $data

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
51

For unnamed array (JSON like: ["value1", "value2"]), it would be:

<ul data-bind="foreach: $root">
 <li data-bind="text: $data"></li>
</ul>

$root keyword does the trick.

Nenad
  • 24,809
  • 11
  • 75
  • 93
  • Yeah - the above code was for use with jQuery templates. Having ditched that long ago and went with the native knockout templates, this indeed how to do it. – Adam Rackis Feb 04 '13 at 20:29
  • Actually, `$root` represents the object passed to `ko.applyBindings`. So this would only work if you did something like `ko.applyBindings(["value1", "value2"], document.getElementById("MyValueList"));`. If you're going to be binding anything else on the page, you would be better served having this as a named member on your viewmodel, or you could write the array to the binding like so: `foreach: ["value1", "value2"]`. See http://knockoutjs.com/documentation/binding-context.html for more info. – CptRobby Sep 08 '16 at 13:19