3

I generated table data and table columns dynamically in angularjs. My table is

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

But I want my table to be displayed like this :

Name    Hobby

XXXX
        Music
        Cricket
        Books
YYYY
        Tennis
        Books
        Drawing

I used the following code to generate 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 can't use similar to this

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

because my table headers are created dynamically

How I can do this in angularjs?

Priya
  • 591
  • 1
  • 8
  • 23

3 Answers3

3

here is 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 render array in your table

freethinker
  • 2,257
  • 4
  • 26
  • 49
1

You could do this thing on markup itself, no need of sorting or filtering an 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

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
0

I would use ng-table You will be able to easily sort, filter and group your table.

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299