user6839132
user6839132

Reputation:

AngularJs: Convert json string to html table

I am an absolute newbie to angularjs and i have been making my hands dirty from the past 3 days. Now, the requirement is to convert a json string from the rest end point to tabular data. Here is the code i am trying.

 $scope.getDataCatalogue = function(){

       $http.get('http://api.geosvc.com/rest/US/84606/nearby?apikey=485a35b6b9544134b70af52867292071&d=20&pt=PostalCode&format=json')
           .success(function(data, status, headers, config){
                 //do something with your response
                 $scope = data;
           })
           .error(function(error){
                 console.log("not world");
           });
  }

   $scope.getDataCatalogue = function(){
    alert('getDataCatalogue');
   }

Now,how can i convert the json to grid from the data. Is this the right way to approach the problem.

Upvotes: 1

Views: 1550

Answers (2)

Nikhil Nanjappa
Nikhil Nanjappa

Reputation: 6652

If you have a fixed structure coming out of the data then you can simply make use of ng-repeat to iterate through the object(data) and display it on your pre-created table. Fiddle

Example shown below:

Considering this is your object which your assigning to a $scope variable name people. $scope.people = data;

[
    {
      id: 1,
      firstName: "Peter",
      lastName: "Jhons"
    },
    {
      id: 2,
      firstName: "David",
      lastName: "Bowie"
    }
]

In your controller:

.success(function(data, status) {
    $scope.people = data;
 });

In your HTML :

<table>
    <tr>
        <th>Id</th>
        <th>First Name</th>
        <th>Last Name</th>
    </tr>
    <tr ng-repeat="person in people">
        <td>{{person.id}}</td>
        <td>{{person.firstName}}</td>
        <td>{{person.lastName}}</td>
    </tr>
</table>

Upvotes: 2

Amygdaloideum
Amygdaloideum

Reputation: 4923

Either do it yourself in the view:

<table>
    <thead>
        <tr>
            <th>header 1</th>
            <th>header 2</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="row in data">
            <td>{{row.attribute1}}</td>
            <td>{{row.attribute2}}</td>
        </tr>
    </tbody>
</table>

Or use a library like ui-grid to render a more advanced table.

Upvotes: 0

Related Questions