1

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>
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • 1
    http://learn.knockoutjs.com/#/?tutorial=custombindings (step 4 in this tutorial). – Jose Luis May 23 '18 at 12:28
  • Thanks. Not really sure how they relates to my layout structurel. If it helps, all my stuff is hard coded. It's not going to change from a database or anything. –  May 23 '18 at 12:40

1 Answers1

0

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>
Bivo Kasaju
  • 1,143
  • 3
  • 13
  • 28
  • Thanks for the response. I'm afraid that still only provided one star element instead of 5 (if we're referring to the data in my example) –  May 23 '18 at 14:10
  • my bad, updated the answer that should work.. working jsfiddle here http://jsfiddle.net/LkqTU/47927/ – Bivo Kasaju May 23 '18 at 14:39
  • That's amazing. Thank you for the effort! That's much appreciated! –  May 24 '18 at 07:24