angular-datatables icon indicating copy to clipboard operation
angular-datatables copied to clipboard

Render table from array

Open edenchen123 opened this issue 12 years ago • 6 comments

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

edenchen123 avatar Oct 24 '14 18:10 edenchen123

There are several way to render your DataTable:

  1. Your data is in your DOM.
  2. Your data is fetched with Ajax.
  3. Your data is fetched with a promise.
  4. 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.

l-lin avatar Oct 24 '14 18:10 l-lin

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!

estaub avatar Oct 06 '15 18:10 estaub

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');

l-lin avatar Oct 06 '15 18:10 l-lin

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.

estaub avatar Oct 06 '15 19:10 estaub

Its easy, use $timeout service, and return array data.

DTOptionsBuilder.fromFnPromise($timeout(function() {
    return arrayData;
}))

jorgemarcondes avatar Jun 22 '16 14:06 jorgemarcondes

This worked for me and is arguably a bit clearer than $timeout?

DTOptionsBuilder.fromFnPromise(function() {return $q.when(arrayData)})                                    

ErichBSchulz avatar Dec 18 '16 06:12 ErichBSchulz