bobthebuilder4t5 bobthebuilder4t5 - 1 year ago 45
AngularJS Question

How to avoid populating a table in a repetitive manner?

Right now I have a table that looks like this:

enter image description here

The HTML for this table looks like this (I only included a brief snippet because the rest of the HTML looks the same):

<table class="table table-bordered table-condensed">
<tr>
<th>Days</th>
<th>Date</th>
<th>Calories</th>
<th>Happiness</th>
<th>Hunger</th>
<th>Motivation</th>
</tr>
<tr>
<td>1</td>
<td id="day">{{dayArray[0]}}</td>
<td id="calorie">{{calorieArray[0]}}</td>
<td><input placeholder="0" /></td>
<td><input placeholder="0" /></td>
<td><input placeholder="0" /></td>
</tr>
<tr>
<td>2</td>
<td id="day">{{dayArray[1]}}</td>
<td id="calorie">{{calorieArray[1]}}</td>
<td><input placeholder="0" /></td>
<td><input placeholder="0" /></td>
<td><input placeholder="0" /></td>
</tr>
<tr>
<td>3</td>
<td id="day">{{dayArray[2]}}</td>
<td id="calorie">{{calorieArray[2]}}</td>
<td><input placeholder="0" /></td>
<td><input placeholder="0" /></td>
<td><input placeholder="0" /></td>
</tr>
<tr>


I am using an array to populate the date because dependent on what the user chooses earlier on in the page, the date changes. The same goes for calories. I am using AngularJS's data binding to do this.

Does anyone have an idea of how to change the table's HTML to make it less repetitive? I have heard that anytime you begin to start copying and pasting things, it's a sign that you're writing bad code :(

Ero Ero
Answer Source

use an ng-repeat

<table class="table table-bordered table-condensed">
   <tr>
       <th>Days</th>
       <th>Date</th>
       <th>Calories</th>
       <th>Happiness</th>
       <th>Hunger</th>
       <th>Motivation</th>
  </tr>
  <tr ng-repeat="day in dayArray">
      <td>{{ $index + 1 }}</td>
      <td id="day-{{$index}}">{{day}}</td>
      <td id="calorie-{{$index}}">{{calorieArray[$index]}}</td>
      <td><input placeholder="0" /></td>
      <td><input placeholder="0" /></td>
      <td><input placeholder="0" /></td>
   </tr>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download