获取AngularJS中的未知对象并对其进行循环
Fetch and loop over unknown objects in AngularJS
我在ASP.NET MVC中研究泛型已经有一段时间了,我也考虑过其他语言上的泛型,尤其是AngularJS中的泛型。
假设我有两个样本端点:
www.listofstudents.com/all
和www.listofteachers.com/all
它将返回2个对象类型students
或teachers
。
我想知道如何处理这种情况。过程将是:
- 从所需的终结点获取
- 确定对象类型
- 遍历对象的
properties
以创建表头 - 遍历这些值并将它们显示在表中
以下是我迄今为止所尝试的,只是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
中建立的密钥顺序。
相关文章:
- 循环对象时更新页面上的DIV元素
- 如何在循环对象时有条件地使用数据
- Javascript循环对象
- 如何循环对象中的javascript对象并查找属性
- JSON.parse在循环对象上未出错
- TypeError:分析隐藏值时,javascript中的循环对象值
- 以随机顺序定位和循环对象
- 循环对象文本数组并匹配客户
- for/in 循环对象到数组
- Javascript 不等待 For 循环.对象值不变
- 循环对象的顺序只能在迭代期间中断
- 循环对象以获取索引值
- Javascript 循环 + 对象问题:如何使用循环获取对象中的必需项
- 使用 requestAnimationFrame 的 JS 游戏循环 - 对象函数只调用一次
- 循环对象上的垃圾回收
- Javascript循环对象时打印页面
- 循环对象数组,直到lat/lng不为零
- javascript中循环对象的问题
- 循环对象数组
- 使用字符串数组循环对象