infinity
infinity

Reputation: 719

Create a HTML table from JSON

I have a rails application that I'm converting to be angularjs.

From a rest API, I am getting JSON like:

[{"id":1,"products":{"type":"Mustang","color":"blue"},"created_at":"2013-12-02T01:05:20.956Z","updated_at":"2013-12-02T01:05:20.956Z"}]

My angular at the moment just loops through the JSON and prints out the entire data column:

<tr ng-repeat="row in rows">
    <td><a href='#'>THIS IS -> </a>{{row.data}}</td>
</tr>

Basically, I'd like to take from the data column, the key and the value, and create a HTML table based off it. The problem is the data can vary, so not always will a key/value like: " type: Mustang" be the first, and sometimes a value will be empty but a key won't.

I asked a similar question a while back, and got a fantastic answer. The Solution 2 works perfectly for Ruby, but I'd like to convert it to angularjs for my project.

Thanks for all help!

Upvotes: 0

Views: 903

Answers (2)

Bastien Caudan
Bastien Caudan

Reputation: 4490

To convert your Ruby solution in an AngularJS fashion, you can use a third party library like UnderscoreJS to transform your JSON as you want.

So, you can first retrieve the list of products from your rest API response:

var rows = [{"id":1,"products":{"type":"Mustang","color":"blue"},"created_at":"2013-12-02T01:05:20.956Z","updated_at":"2013-12-02T01:05:20.956Z"}, ...]
$scope.products = _.pluck(rows, 'products'); // make a list of the products property of each row

Then, you can compute your headers:

$scope.headers = _.chain($scope.products)
                  .map(_.keys) // take the keys of each product
                  .reduce(function(a, b) {
                            return _.union(a, b);
                          }, []) // merge all keys without double
                  .value();

Finally, you can display your table by iterating on headers and products:

<table>
  <tbody>
    <tr>
      <th ng-repeat="key in headers">{{ key }}</th>
    </tr>
    <tr ng-repeat="product in products">
      <td ng-repeat="key in headers">{{ product[key] }}</td>
    </tr>
  </tbody>
</table>

If a product has not a given key then it will not display anything.

Take a look at this plunker.

An utility library like Underscore is really convenient to manipulate data in a functional fashion. I advise you to look over the API and documentation.

Upvotes: 1

Darryl
Darryl

Reputation: 1451

You can set this up as a directive in place of ng-repeat (which is just a directive) and follow the logic from your Ruby code.

or

You can use ng-repeat and in place of {{row.data}} use a function with row.data as the parameter. The function can then handle the necessary checking for key/value.

Darryl

Upvotes: 0

Related Questions