简体   繁体   中英

How to load an angular-datatables table with a javascript array in the controller

I want to load an angular-datatable with a javascript array but if I try this I get this error

DataTables warning: table id=DataTables_Table_0 - Ajax error. For more information about this error, please see http://datatables.net/tn/7

it looks like it is trying to access some kind of URL

I want to load it from my angularjs controller, here is my html code

<div class="table-responsive">
        <table datatable="" 
               dt-options="ctrl.dtOptions" 
               dt-columns="ctrl.dtColumns" 
               class="table table-striped table-bordered table-hover"
               width="100%">
        </table>
    </div>

and here is the code inside my angularjs controller:

var data = [{
                    "name": the name,
                    "lastname": "xx",
                    "age": 2
                }, {
                    "name": the name two,
                    "lastname": "yy",
                    "age": 3
                }];




            vm.dtOptions = DTOptionsBuilder.fromSource(JSON.stringify(data))
                    .withOption('createdRow', createdRow)
                    .withOption('stateSave', true)
                    .withPaginationType('full_numbers')
                    // Add Bootstrap compatibility
                    .withBootstrap()
                    // Active Responsive plugin
                    .withOption('responsive', true);
            vm.dtColumns = [
                DTColumnBuilder.newColumn(null).withTitle('Actions').notSortable()
                        .renderWith(actionsHtmlEstatus),
                DTColumnBuilder.newColumn('name').withTitle('Name'),
                DTColumnBuilder.newColumn('lastname').withTitle('lastname'),
                DTColumnBuilder.newColumn('age').withTitle('age')
            ];

When you have a static JSON / object literal then simply use the data option :

vm.dtOptions = $scope.dtOptions = DTOptionsBuilder.newOptions()
   .withOption('data', data) // <---- like this
   .withOption('createdRow', createdRow)
   .withOption('stateSave', true)
   ...

demo using the sample array in OP -> http://plnkr.co/edit/s2RybDQ8WV27jPOf4VQA?p=preview

You can't use .fromSource as it always will do an ajaxUrl request. instead you can use .fromFnPromise() . You need to Put your JSON into a function which returns an deferred.promise.

check below pen for working example:

http://codepen.io/anon/pen/jrLpZX

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM