angularjs - 在页面加载时使用 AngularJS 将 json 绑定(bind)到 HTML 表

标签 angularjs

我有一个简单的概念验证,用作学习一些 AngularJS 的基础。该代码在 HTML 表格中显示一些 JSON 数据,如下所示:

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

    };

}

fiddle 在这里:http://jsfiddle.net/TUJ9D/

这很好用;当您单击该链接时,它会调用“loadPeople”并将 json 拉入表中。但是,我想做的是在页面加载时绑定(bind)它,这样用户就不必手动单击链接来查看表中的数据。

我想知道最好的方法是什么? Instinct 告诉我在页面加载时使用 jquery 调用该函数,但是我不知道这是否是一种好方法,或者 Angular 本身是否可以以更好的方式做到这一点。

谢谢各位。

最佳答案

只需调用 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/

关于angularjs - 在页面加载时使用 AngularJS 将 json 绑定(bind)到 HTML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18769457/

相关文章:

javascript - 在 Polymer Web 组件中使用 AngularJS

javascript - 如何将应用程序从 Sublime Text 引入 Web IDE 进行共享?

angularjs - 如何在 jasmine 中对条件语句进行单元测试

javascript - 为什么我对 PHP 页面的 Angular POST 请求没有设置 POST 数组?

javascript - 如何在 AngularJS 中使用 CKEditor 上传图像?

javascript - 使用 Watchify 时,Browserify + Babelify Gulp 任务不会终止

javascript - 未调用模板代码中的函数

angularjs - 动态数字键上的 Angular ng-repeat 不起作用

javascript - 如果 Div 上的条件为真,如何防止提交表单?

html - 使用 angular、css、html 手动复制 bootstrap typeahead-show-hint