如何在控制器中加载一个带有javascript数组的angular-datatable表

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

本文关键字:一个 javascript 数组 angular-datatable 控制器 加载      更新时间:2023-09-26

我想用javascript数组加载一个angular-datatable但如果我尝试这样做,我会得到这个错误

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

它看起来像是试图访问某种URL

我想从angularjs控制器加载它,这是我的html代码

<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>

下面是我的angularjs控制器中的代码:

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

当你有一个静态JSON/对象文字,那么只需使用 data 选项:

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

使用OP ->中的示例数组演示 http://plnkr.co/edit/s2RybDQ8WV27jPOf4VQA?

你不能使用.fromSource,因为它总是会做一个ajaxUrl请求。相反,您可以使用.fromFnPromise()。你需要把JSON放到一个返回deferred.promise的函数中。

检查钢笔下面的工作示例:

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