Render table from array
Do we have a the way to load data source from an array? I am doing this now: DTOptionsBuilder.fromFnPromise($q.defer().promise.then(function(){ return []; })); so weird
There are several way to render your DataTable:
- Your data is in your DOM.
- Your data is fetched with Ajax.
- Your data is fetched with a promise.
- You render using the "Angular way".
So if you have an array you want to display, you can use the 4th way. You just need to bind the array to your $scope and it's all good.
Look at the documentation for more info.
I suspect the original poster was trying to ask my question, which is:
Does fromFnPromise work with a promise that returns an array of records, just as "config.data:" would use? If not, what format(s) ARE supported?
I ask because it's not working with an array - or I'm doing something else wrong!
By default, angular-datatables set the dataSrc, which is the attribute name where the array of data is stored, to an empty array. Meaning it expects to have an array of data and not an object which contains the array in an attribute.
What @edenchen123 wrote is not correct. withFnPromise is expecting a function that returns the promise (which resolve an array of data).
So it should have been instead something like this:
DTOptionsBuilder.fromFnPromise(function() {
return somethingThatReturnsAPromise();
});
There are more info in the documentation, HTML, JS codes and the expected data.
If you server returns an object instead, for example:
{
"tableData": [{
"id": 123,
"firstName": "Foo",
"lastName": "Bar"
}]
}
then you need to use the withDataProp method:
DTOptionsBuilder.fromFnPromise(function() {
return somethingThatReturnsAPromise();
}).withDataProp('tableData');
Thanks - that led me to the "something else wrong" I was doing, which was more-or-less the same as @edenchen123 - a missing "return" of the promise.
Its easy, use $timeout service, and return array data.
DTOptionsBuilder.fromFnPromise($timeout(function() {
return arrayData;
}))
This worked for me and is arguably a bit clearer than $timeout?
DTOptionsBuilder.fromFnPromise(function() {return $q.when(arrayData)})