Skip to main content

foreach with if condition in knockout js

Hello everyone, I am going to share the code sample for how to use foreach loop and if condition in knockoutJs as given below.

Table of Contents

1. foreach loop in observable array knockout Js 
2. if in observable array knockout Js 
3. List in observable array knockout Js

This is for view code in Knockout Js for foreach loop and if conditions using knockoutjs MVC 4


<div data-bind="foreach: matters">
    <div data-bind="if: dateTime.length > 0">
        <table>
            <tr>
                <td>
                    <label data-bind="text: dateTime"></label>
                </td>
            </tr>
        </table>
    </div>
</div>
<div class="time_data">
    <table>
        <tr>
            <td>
                <img src="~/Images/icon_status.png" /></td>
            <td data-bind="foreach: subMatter">
                <div data-bind="text: $data"></div>
            </td>
            <td>
                <div data-bind="text: hour"></div>
                <a href="#">
                    <img src="~/Images/icon_options.png" />
                </a>
            </td>
        </tr>
    </table>
</div>

This is for viewModel code which use to display each row using foreach on matters collection [matters is a observable array]

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            url: "/MyTimeHome/GetMethod/",
            type: 'post',
            data: "{'matterId':'1' }",
            contentType: 'application/json',
            success: function (result) {
                // call to view model              
                getViewModel(result);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                var errorMessage = '';
                $('#message').html(jqXHR.responseText);
            }
        });

        function getViewModel(result) {
            // Define a "matter" class.
            var matter = function (dateTime, hour, subMatter) {
                this.dateTime = dateTime;
                this.hour = hour;
                this.subMatter = ko.observableArray(subMatter);
            }
         
            var viewModel = {
                matters: [],
                showRenderTimes: ko.observable(false)
            };

            // push all data in view model
            for (var i = 0; i < result.length; i++) {
                var matterRow = new matter(result[i].createdOn + " | " + result[i].totalHours, result[i].totalHours,
                    [result[i].matterTitle, result[i].MyProperty1, result[i].matterComment]);

                viewModel.matters.push(matterRow);
               
            }
            // bind view model to knockout
            ko.applyBindings(viewModel);
        } 
    });

</script>