获取AngularJS中的未知对象并对其进行循环

Fetch and loop over unknown objects in AngularJS

本文关键字:循环 对象 AngularJS 未知 获取      更新时间:2023-09-26

我在ASP.NET MVC中研究泛型已经有一段时间了,我也考虑过其他语言上的泛型,尤其是AngularJS中的泛型。

假设我有两个样本端点:

www.listofstudents.com/allwww.listofteachers.com/all

它将返回2个对象类型studentsteachers

我想知道如何处理这种情况。过程将是:

  1. 从所需的终结点获取
  2. 确定对象类型
  3. 遍历对象的properties以创建表头
  4. 遍历这些值并将它们显示在表中

以下是我迄今为止所尝试的,只是angular中使用两个不同端点的典型请求过程:

app.js

var app = angular.module("jsonApp",[]);
app.controller("jsonCtrl", ['$scope', '$http',function($scope, $http){
    $http.get("http://jsonplaceholder.typicode.com/comments")
        .success(function(response){
            $scope.records = response;
        });
    $http.get("http://jsonplaceholder.typicode.com/posts")
        .success(function(response){
            $scope.posts = response;
        });
    }]);

index.html

<table ng-controller="jsonCtrl" class="table">
        <tr>
            <th>AuthorID</th>
            <th>Title</th>
            <th>Body</th>
        </tr>
        <tr ng-repeat="post in posts | limitTo: 10">
            <td>{{post.userId}}</td>
            <td>{{post.title}}</td>
            <td>{{post.body}}</td>
        </tr>
    </table>

如果您所问的只是如何获取表标题的属性名称,那么这样的东西就足够了(假设每个post都有相同的键)

$http.get("http://jsonplaceholder.typicode.com/posts").then(function(response) {
    $scope.data = response.data;
    $scope.headers = Object.keys(response.data[0] || {});
});

请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

然后您可以使用ng-repeat

<table>
<thead>
    <tr>
        <th ng-repeat="header in headers">{{::header}}</th>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="item in data">
        <td ng-repeat="prop in headers">{{::item[prop]}}</td>
    </tr>
</tbody>
</table>

嵌套循环是为了维护在headers中建立的密钥顺序。