JSON绑定到HTML表在页面加载AngularJS [英] Bind json to HTML table with AngularJS on page load

查看:109
本文介绍了JSON绑定到HTML表在页面加载AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我使用为基础的一个简单证明了概念学习一些AngularJS。在code上显示一个HTML表中的一些JSON数据,如下:

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

    };

}

一个小提琴是在这里: http://jsfiddle.net/TUJ9D/

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

这很好地工作;当你点击链接,它调用loadPeople和JSON被拉入表。不过,我希望做的是绑定这个当页面加载,因此用户不必手动点击链接查看该表中的数据。

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.

我不知道该怎么做,这是最好的办法吗?本能告诉我打电话给同在页面加载jQuery的功能,但我不知道这是一个很好的方法或角是否能以更好的方式本身。

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.

感谢乡亲。

推荐答案

只需拨打您的控制器上的负载funcion。

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

这篇关于JSON绑定到HTML表在页面加载AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆