2013年7月18日木曜日

How to render JSON key-value properties using AngularJS

See a demo at JSFIDDLE


When you are developing REST API on server side, you sometimes want to have a page that renders JSON data in a bit nice way than a row JSON view (that most browsers do good job rendering, but still somewhat hard to read)

To render JSON data in a simple HTML table (or whatever) format with minimum AngularJS coding, here is how.


JSON Data

Let's say, you have a JSON data (this is from AngularJS Tutorial) available from a controller ("C" part of MVC)

function PhoneListCtrl($scope) {
    $scope.phones = [
        {
            "name": "Nexus S",
            "snippet": "Fast just got faster with Nexus S.",
            "age": 0},
        {
            "name": "Motorola XOOM with Wi-Fi",
            "snippet": "The Next, Next Generation tablet.",
            "age": 1},
        {
            "name": "MOTOROLA XOOM",
            "snippet": "The Next, Next Generation tablet.",
            "age": 2}
    ];
}

HTML markup 

...with AngularJS expressions. Note the expression "(key, value) in phone" below. (By the way, this is "V" part of MVC, and "phones" data is the "M" part, just for the sake of completeness!)

<div>
  <h1>Phones</h1
  <div ng-repeat="phone in phones">
    <h2>{{phone.name}}</h2>
    <table border="1px">
      <tr ng-repeat="(key,value) in phone">
        <td>{{key}}</td>
        <td>{{value}}</td>
      </tr>
    </table>
  </div>
</div>

Result

Phones

Nexus S

age0
nameNexus S
snippetFast just got faster with Nexus S.

Motorola XOOM with Wi-Fi

age1
nameMotorola XOOM with Wi-Fi
snippetThe Next, Next Generation tablet.

MOTOROLA XOOM

age2
nameMOTOROLA XOOM
snippetThe Next, Next Generation tablet.

0 件のコメント:

コメントを投稿