how to iterate through knockout viewmodel collection

戏子无情 提交于 2019-12-25 01:46:03

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/50081008/how-to-iterate-through-knockout-viewmodel-collection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!