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.
Example:
json data:
[
{
"id": "2",
"city": "Baltimore",
"state": "MD",
},
{
"id": "5",
"city": "Boston",
"state": "MA",
},
{
"id": "8",
"city": "Malvern",
"state": "PA",
},
]
Column Headers:
id, city, state
Can someone please help with this?
Being faced with the same problem, I actually found an easier to implement and much simpler (and safer because of not using $compile) solution.
The only change needed to be made to the html is the addition of an
ng-if
:What happens is that angular will delay the creation of this node till
columnsReady
has any value. So now in your code you can get the data you need, and when you have it, you can just setcolumnsReady
totrue
and angular will do the rest.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 :First, to avoid instant initialization remove the
datatable
directive from the markup and give the<table>
anid
instead, i.e :Then load the data resource, build
dtColumns
anddtOptions
and finally inject thedatatable
attribute and$compile
the<table>
using theid
:This should work with any "array of objects" resource
Demo -> http://plnkr.co/edit/TzBaaZ2Msd9WchfLDLkN?p=preview
NB: Have cleaned up the example JSON, I guess it was a sample and not meant to be working with trailing commas.
Below code which will give you table dynamically based on data
HTML
JS
}
data.json