angularBeginner angularBeginner - 2 months ago 25
JSON Question

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.

Answer

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>