Tuesday, February 24, 2015

Render json in table using AngularJs

1) HTML

<div ng-app="myApp">
<div ng-controller="PeopleCtrl">
    <p>    Click <a ng-click="loadPeople()">here</a> to load data.</p>
<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>
</div>
</div>
       
2) Controller.js

//Declare json
var mockDataForThisTest = "json=" + encodeURI(JSON.stringify([
    {
    id: 1,
    firstName: "Peter",
    lastName: "Jhons"},
{
    id: 2,
    firstName: "David",
    lastName: "Bowie"}
]));
//end of declaring json

var app = angular.module('myApp', []);//define app MyApp should be equal to  ng-app="myApp" in HTML

//controller will get call from ng-controller="PeopleCtrl"
function PeopleCtrl($scope, $http) {

    $scope.people = [];

    $scope.loadPeople = function() {
        var httpRequest = $http({
            method: 'POST',
            url: '/echo/json/',
            data: mockDataForThisTest

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

    };

}


No comments:

Post a Comment