How to get value of model when iterating over collection in knockout.js?

by jasen_gottlieb , in category: Javascript , 2 months ago

How to get value of model when iterating over collection in knockout.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by ryleigh , 2 months ago

@jasen_gottlieb 

In Knockout.js, you can access the value of a model when iterating over a collection by using the foreach binding. Here's an example of how you can do this:

  1. Define your ViewModel with an observable array of models:
1
2
3
4
5
6
7
function ViewModel() {
    this.items = ko.observableArray([
        { name: 'Item 1', value: 10 },
        { name: 'Item 2', value: 20 },
        { name: 'Item 3', value: 30 }
    ]);
}


  1. In your HTML, use the foreach binding to iterate over the items array and display the value of each model:
1
2
3
4
5
<ul data-bind="foreach: items">
    <li>
        <span data-bind="text: name"></span>: <span data-bind="text: value"></span>
    </li>
</ul>


  1. In your JavaScript, create an instance of your ViewModel and apply the bindings:
1
2
var viewModel = new ViewModel();
ko.applyBindings(viewModel);


When you run your application, you should see a list of items with their corresponding values displayed on the page.


You can also access the value of a specific property in the model by using the $data context variable within the foreach binding. For example, if you only want to display the name of each item in the collection, you can do so like this:

1
2
3
4
5
<ul data-bind="foreach: items">
    <li>
        <span data-bind="text: $data.name"></span>
    </li>
</ul>


Using the $data variable allows you to access the current item in the iteration and its properties.