您可以使用 Angular 填充表.js而无需硬编码列名
Can you populate a table with Angular.js without hardcoding column names?
我有一个简单的Angular.js应用程序,它从mysql数据库中获取表格数据并将其显示在一个简单的引导表中。我正在使用下面的代码来显示表列名称,而无需单独硬编码它们......
HTML:
<table class="table">
<thead>
<tr style="background:lightgrey">
<th ng-repeat="column in columns"> {{ column }} </th>
</tr>
</thead>
在控制器中,我用这样的东西创建了"$scope.columns"......
var columnNames = function(dat) {
var columns = Object.keys(dat[0]).filter(function(key) {
if (dat[0].hasOwnProperty(key) && typeof key == 'string') {
return key;
}
});
return columns;
};
DataFactory.getTables(function(data) {
$scope.columns = columnNames(data);
$scope.tables = data;
});
这按预期工作,很棒,但是其余数据呢?例如,我的表格主体目前看起来像这样......
HTML:
<tbody>
<tr ng-repeat="x in tables ">
<td> {{ x.id}} </td>
<td> {{ x.name }} </td>
<td> {{ x.email }} </td>
<td> {{ x.company }} </td>
</tbody>
我试过使用两个这样的循环...
HTML:
<tbody>
<tr ng-repeat="x in tables">
<td ng-repeat=“column in columns”> {{ x.column }} </td>
</tr>
</tbody>
但是这段代码不起作用,那么是否可以在不对 HTML 中的列名进行硬编码的情况下用 angular 填充表,如果是这样,最有效的方法是什么?
您可能
想尝试此 https://jsfiddle.net/8w2sbs6L/。
<div data-ng-app="APP">
<table ng-controller="myController" border=1>
<thead>
<tr>
<td ng-repeat="column in columns">{{column}}</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in tables">
<td ng-repeat="column in columns">{{x[column]}}</td>
</tr>
</tbody>
</table>
</div>
<script>
'use strict';
angular.module('APP', [])
.controller('myController', ['$scope', function($scope){
$scope.tables = [
{
"column1":"row1-column1",
"column2":"row1-column2",
"column3":"row1-column3",
"column4":"row1-column4"
},
{
"column1":"row2-column1",
"column2":"row2-column2",
"column3":"row2-column3",
"column4":"row2-column4"
}
];
$scope.columns = [
"column1",
"column2",
"column3",
"column4"
];
}]);
</script>
相关文章:
- 如何在JS中编码URL并在PHP中解码
- Json在js中对数据循环进行编码
- 使用node.js中的windows 1252对字符串进行编码
- 无法读取js中的php JSON编码数据
- 如何在 JS 上使用 PHP 变量 (fetch_array) ?(JSON 编码)
- 未知编码:僵尸.js中的 iso-8859-1 错误
- 使用webpack时如何避免这种硬编码的index.js
- Angular JS编码的双引号不起作用
- 为什么URI编码('#')锚导致404,以及如何在JS中处理它
- node.js请求编码(谷歌翻译)
- 正在提交带有base64编码文件的Dropzone.js
- MVC:如何使用JavaScriptSerializer将代码解码为c#中编码的JS
- 在敲除js中,这两种编码方法有什么区别
- 如何使用JS SDK发布Facebook评分,而无需对应用访问令牌进行硬编码
- 如何使用 Node.js 和 socket.io 设置 gzip 编码
- 使用 Matt Diamond 的记录器.js在 javascript 中编码 8 位 wav
- 以 json 或 url 编码格式发送 js 模型
- 编码JS下划线_.从零开始扩展
- JSFiddle代码在实现到网站时不工作,在Dreamweaver中编码.JS
- 用java编码(js到java)