如何将本地 JSON 对象与 angular-数据表一起使用

How to use a local JSON object with angular-datatables

我想这样做:

testdata = [{"id":"58",...}]; // local object

$('#test').dataTable({
    "aaData": testdata,
    "aoColumns": [
        { "mDataProp": "id" }
    ] });

使用 angular-数据表模块。我试过这个:

控制器

$scope.dtOptions = DTOptionsBuilder.fromSource('[{"id": 1}]')
        .withDataProp('data')
        .withBootstrap()
        .withPaginationType('full_numbers');
$scope.dtColumns = [
        DTColumnBuilder.newColumn('id').withTitle('ID')
];

查看

<table datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="table table-striped table-bordered"></table>

但它根本不起作用,我收到此错误消息:

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

此外,我无法使用任何 Ajax 选项从 URL 获取 json 数据,因为我的 angularjs 项目使用 Express 和其他 API,所以我在尝试使用 GET/POST URL 获取我的数据时收到 401 未授权错误,例如“/api/data/getJsonData”。

有什么想法吗?谢谢。

您不能使用 .fromSource,因为它总是会执行 ajaxUrl 请求。但是您可以改用 .fromFnPromise() 。将你的 JSON 放入一个 returns 和 deferred.promise.

的函数中

我遇到了与 OP 类似的问题,Mica 的回答对我指明了正确的方向很有帮助。我使用的解决方案如下:

var getTableData = function() {
    var deferred = $q.defer();
    deferred.resolve(myTableDataObject); 
    return deferred.promise;
};

然后在 DTOptionsBuilder 中使用它:

$scope.dtOptions = DTOptionsBuilder.fromFnPromise(getTableData)
    .withPaginationType('full_numbers');

我是 Angular 的新手,实际上 JavaScript,所以可能有更多 elegant/correct 的方法来做到这一点,但它对我有用。