如何在数据表angular中基于JSON动态填充表值? [英] How to populate table values dynamically based on JSON in datatable angular?
问题描述
我正在使用 Angular-Datatables .我需要能够根据返回的数据动态创建表.换句话说,我不想指定列标题.
I'm using Angular-Datatables. I need to be able to dynamically create the table based on the data that is being returned. In other words, I do not want to specify the column headers.
示例:
json数据:
[
{
"id": "2",
"city": "Baltimore",
"state": "MD",
},
{
"id": "5",
"city": "Boston",
"state": "MA",
},
{
"id": "8",
"city": "Malvern",
"state": "PA",
},
]
列标题:
id,城市,州
有人可以帮忙吗?
推荐答案
这实际上是一个好问题!对于传统的jQuery dataTables来说,这不是问题,但是对于角度数据表,我们有另一种声明式设置,这使得分离各种任务更加困难.我们可以使用fromFnPromise
延迟数据填充,但不能阻止dataTable在需要之前实例化.我想我已经找到了一个可靠的解决方案:
That is actually a good question! With traditional jQuery dataTables it is not a problem, but we have a different kind of declarative setup with angular dataTables, making it more difficult to separate the various tasks. We can delay the population of data with fromFnPromise
, but not prevent the dataTable from being instantiated before we want it. I think I have found a solid solution :
首先,为避免立即初始化,请从标记中删除datatable
指令,并给<table>
一个id
,即:
First, to avoid instant initialization remove the datatable
directive from the markup and give the <table>
an id
instead, i.e :
<table id="example" dt-options="dtOptions" dt-columns="dtColumns" />
然后加载数据资源,构建dtColumns
和dtOptions
,最后使用id
注入datatable
属性和$compile
<table>
:
Then load the data resource, build dtColumns
and dtOptions
and finally inject the datatable
attribute and $compile
the <table>
using the id
:
$http({
url: 'data.json'
}).success(function(data) {
var sample = data[0], dtColumns = []
//create columns based on first row in dataset
for (var key in sample) dtColumns.push(
DTColumnBuilder.newColumn(key).withTitle(key)
)
$scope.dtColumns = dtColumns
//create options
$scope.dtOptions = DTOptionsBuilder.newOptions()
.withOption('data', data)
.withOption('dataSrc', '')
//initialize the dataTable
angular.element('#example').attr('datatable', '')
$compile(angular.element('#example'))($scope)
})
这应该与任何对象数组"资源一起使用
演示-> http://plnkr.co/edit/TzBaaZ2Msd9WchfLDLkN?p=preview
This should work with any "array of objects" resource
Demo -> http://plnkr.co/edit/TzBaaZ2Msd9WchfLDLkN?p=preview
注意:清理了示例JSON,我想它只是一个示例,并不意味着要使用尾随逗号.
NB: Have cleaned up the example JSON, I guess it was a sample and not meant to be working with trailing commas.
这篇关于如何在数据表angular中基于JSON动态填充表值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!