8

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.

Dan
  • 5,836
  • 22
  • 86
  • 140

2 Answers2

6

Just call the load function 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/

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Beterraba
  • 6,515
  • 1
  • 26
  • 33
1

you can simple add ng-init="loadPeople()" directive inside your <div>.

i.e.

<div ng-controller="PeopleCtrl" ng-init="loadPeople()">
Alfred Roa
  • 223
  • 1
  • 5
  • 10