knockout.js Bindings Foreach


Example

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">
    </div>
</div>
 
<script type="text/javascript">
    var contactViewModel = function (data) {
        this.name = ko.observable(data.name);
        this.info = ko.observable(data.info);
    };

    ko.applyBindings({
        contacts: [
            new contactViewModel({name:'Erik', info:'Erik@gmail.com'}),
            new contactViewModel({name:'Audrey', info:'Audrey@gmail.com'})
        ]
    });
</script>

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