how to iterate through knockout viewmodel collecti

2019-08-23 09:21发布

Iam not able to display product items with Knockout.js library.

Html

<p>First product: <strong data-bind="text: products[0].description"></strong></p>

<tbody data-bind="foreach: products">
    <tr>
        <td data-bind="text: id"></td>
        <td data-bind="text: description"></td>
    </tr>
</tbody>

JavaScript

<script type='text/javascript'>

            $(function () {

                var json = {
                    "products": [
                        { "id": 1, "description": "product A" },
                        { "id": 2, "description": "product B" },
                        { "id": 3, "description": "product C" }
                    ]
                }

                function viewModel() { 
                    this.products = json.products;
                }

                ko.applyBindings(new viewModel());

            });
</script>

I do not get any error message, but i see only "First product:" text. What am I missing ?

标签: knockout.js
1条回答
神经病院院长
2楼-- · 2019-08-23 10:22

I got it working in the follwing jsfiddle: https://jsfiddle.net/3np0hqp7/2/

Html:

<p>First product: <strong data-bind="text: products[0].description"></strong></p>

<table>
<tbody data-bind="foreach: products">
    <tr>
        <td data-bind="text: id"></td>
        <td data-bind="text: description"></td>
    </tr>
</tbody>
</table>

JS:

(function() {
var viewModel = { 
  products: [
    { id: 1, description: "product A" },
    { id: 2, description: "product B" },
    { id: 3, description: "product C" }
  ]
}

ko.applyBindings(viewModel);
}());

You were missing the parenthesis () at the end of the main function, to denote that the function should be executed right away. Furthermore, you can create observables for two-way binding.

查看更多
登录 后发表回答