Dan Dan - 3 months ago 15
AngularJS Question

Bind json to HTML table with AngularJS on page load

I have a simple proof-of-concept I'm using as a base to learn some AngularJS. The code displays some JSON data in an HTML table, as follows:

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>


JS:

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


var app = angular.module('myApp', []);

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;
});

};

}


A fiddle is here: http://jsfiddle.net/TUJ9D/

This works nicely; when you click the link, it calls 'loadPeople' and the json is pulled into the table. However, what I'd like to do is bind this when the page loads, so the user doesn't have to manually click the link to see the data in the table.

I wondered what the best way to do this is? Instinct is telling me to call the function with jquery on page load, but then I don't know if that's a good approach or whether Angular could do this in a better way itself.

Thanks folks.

Answer

Just call the load funcion in your controller.

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;
        });

    };

    $scope.loadPeople();
}

http://jsfiddle.net/TUJ9D/1/

Comments