@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 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 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 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.