In the last few articles, we covered most of the appearance and text bindings. In this article and the next few we shall study control flow bindings. Control flow bindings, as the name suggests control the flow of code execution. In this article we shall study knockoutJS foreach bindings.
KnockoutJS foreach bindings basically repeat html markup according to the number of elements in an array. In each markup repetition you can access the corresponding item in the array. Another very exciting prospect of foreach binding is that if you have an observable array, adding or removing elements from the array shall automatically reflect in the markup. Adding an element will add markup for the element and removing an element shall automatically remove markup.
Usually knockoutJS foreach bindings are used to display list of elements. Take a look at the following example where we simply display the names and ages of some random students in some imaginary school.
Now come to the html view section. Here we have created a table to show the studentName and studentAge parameter from the objects in students array. Notice that the foreach binding is used with the “tbody” tag which means tha whatever is inside this tag shall be repeated the number of times the elements in the students array. Also, during each iteration the values for studentName and studentAge parameters shall be displayed within the
It is important to note here that if you remove or add more student objects in the students array in view model, the information of the newly added students will automatically be added into the table and vice versa.