knockout.js Bindings Foreach


Similar to repeaters used in other languages. This binding will allow you to replicate a block of html for each item in an array.

<div data-bind="foreach:contacts">
    <div class="contact">
        <h2 data-bind="text:name">
        <p data-bind="text:info">
<script type="text/javascript">
    var contactViewModel = function (data) { = ko.observable(; = ko.observable(;

        contacts: [
            new contactViewModel({name:'Erik', info:''}),
            new contactViewModel({name:'Audrey', info:''})

Notice that when we are looping through our context becomes the item within the array, in this case an instance of the contactViewModel. Within a foreach we also have access to

  • $parent - the view model that created this binding
  • $root - the root view model (could also be parent)
  • $data - the data at this index of the array
  • $index - the (observable) zero-based index of the rendered item