How do I format tables in angularjs?

I was generating tabular data and table columns dynamically in angularjs. My table

Name    Hobby
XXXX    Music
XXXX    Cricket
XXXX    Books
YYYY    Tennis
YYYY    Books
YYYY    Drawing

      

But I want my table to display like this:

Name    Hobby

XXXX
        Music
        Cricket
        Books
YYYY
        Tennis
        Books
        Drawing

      

I used the following code to generate the table:

        <tr>
            <th ng-repeat="th in keys">{{th}}</th>
        </tr>
        <tr ng-repeat="x in data ">
            <td ng-repeat="th in keys">
                {{ x[th]}}
            </td>
         </tr>

      

My json looks like this

[{"Name:"XXXX", "Hobby":"Music"},
{"Name:"XXXX", "Hobby":"Cricket"},
{"Name:"XXXX", "Hobby":"Books"},
{"Name:"YYYY", "Hobby":"Tennis"},
{"Name:"YYYY", "Hobby":"Books"},
{"Name:"YYYY", "Hobby":"Drawing"}]

      

I cannot use similar to this

<ng-repeat="(key, value) in players | groupBy: 'team'">

      

because my table headers are generated dynamically

How can I do this in angularjs?

+3


source to share


3 answers


You can do this in the markup itself, no need to sort or filter the array.

Markup



  <table>
    <thead>
      <tr>
        <th ng-repeat="th in keys">{{th}}</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="x in data">
        <td ng-repeat="th in keys">
          <span ng-show="th != 'Name' || (th == 'Name' && data[$parent.$index - 1]['Name'] != x['Name'])">
          {{ x[th]}}
          </span>
        </td>
      </tr>
    </tbody>
  </table>

      

Demo

+1


source


here is a simple javascript solution:

var array = [{"Name":"XXXX", "Hobby":"Music"},
{"Name":"XXXX", "Hobby":"Cricket"},
{"Name":"XXXX", "Hobby":"Books"},
{"Name":"YYYY", "Hobby":"Tennis"},
{"Name":"YYYY", "Hobby":"Books"},
{"Name":"YYYY", "Hobby":"Drawing"}];

 var distinctNames = []

 for (i = 0; i < array.length; i++) { 
   if(distinctNames.indexOf(array[i].Name) === -1){
      distinctNames.push(array[i].Name);
   }
   else{
       array[i].Name = "";
   }
 }

      



DEMO

After this filter, you can display the array in a table

+3


source


I would use ng-table You can easily sort, filter and group the table.

0


source







All Articles