knockout.jsknockout-binding-handlers

Create HTML based on number in array


first time using KO, apologies for what may sound like a silly question.

I have an array full of data. One value is 'stars', which is a number. In my HTML, I would like to create HTML elements based on that value. For example, if the value is four, I would like 4 elements. If the value is 5, I would like 5 elements and so on. I have the rest of the data binding correctly, this is the one part I'm unsure of.

The element I would like to have duplicated is the 'fas fa-star`

Data

scores: [
    {
        title: 'Score One',
        stars: 5,
    },
}

HTML

<ul class="scores" data-bind="foreach: scores">
    <li>
       <div class="title" data-bind="text: title"></div>
       <div class="stars">
           <i class="fas fa-star"></i>
       </div>
     </li>
 </ul>

Solution

  • If you're trying to set the value of class to the value of stars (like <div class="5">), then the following should work:

    <ul class="scores" data-bind="foreach: scores">
        <li>
           <div class="title" data-bind="text: title"></div>
           <div data-bind="attr: { class: stars }">
               <i class="fas fa-star"></i>
           </div>
         </li>
     </ul>
    

    EDIT: Upon re-reading your question, this would be what you're looking for:

    <ul class="scores" data-bind="foreach: scores">
        <li>
           <div class="title" data-bind="text: title"></div>
           <div data-bind="foreach: new Array(stars)"> // <-- replaced scores with stars
               <i class="fas fa-star"></i>
           </div>
         </li>
     </ul>