Koten
Koten

Reputation: 679

jQuery DataTables recreation on data update with socket.io

I'm using jQuery DataTables with socket.io on AngularJS, and I'm pushing an item to the data binding list on a socket message and digesting afterwards. When it happened, the datatable recreated itself instead of just updating the data and not working properly. I'm also randomly get the error *Warning: Cannot reinitialise DataTable, and when I do, the datatable failed to display.

JavaScript

var app = angular.module('App', ['ui.bootstrap','ngAnimate', 'datatables']);
app.factory('socket', function () {
    var socket = io.connect('http://' + document.domain + ':' + location.port + '/t');
    return socket;
});

app.controller('controller', function ($scope, socket, $timeout, DTOptionsBuilder, DTColumnBuilder) {
    $scope.data=[];
    $scope.headers = {'Name':'name','Title','title'}
    socket.on('data', function (d) {
        d = angular.fromJson(d);
        $scope.data.push(d);
        $scope.$digest();
    });

    $scope.dtOptions = DTOptionsBuilder.newOptions().withPaginationType('full_numbers').withOption('bInfo', false);
    $scope.dtColumns = [];
    $scope.dtInstance = {};

    for (key in $scope.headers) {
        $scope.dtColumns.push(DTColumnBuilder.newColumn($scope.headers[key]).withTitle(key));
    }
});

HTML

    <table id="tbl" datatable="ng" dt-options="dtOptions" dt-columns="dtColumns" dt-instance="dtInstance"
           class="table table-striped row-border hover">
        <tr class="fade" ng-model="d"
            ng-repeat="d in data">

Upvotes: 1

Views: 1236

Answers (1)

davidkonrad
davidkonrad

Reputation: 85528

You miss a colon in the headers' literal:

$scope.headers = {'Name':'name','Title' : 'title'}
                                        ^

Hopefully the JSON items pushed into data is valid and the full markup is:

<table id="tbl" datatable="ng" dt-options="dtOptions" dt-columns="dtColumns" dt-instance="dtInstance" class="table table-striped row-border hover">
   <thead></thead>
   <tbody>
       <tr class="fade" ng-model="d" ng-repeat="d in data">
          <td>{{ d.name }}</td>
          <td>{{ d.title }}</td>
       </tr>
   </tbody>
</table>

Use rerender() instead of §digest (why §digest in the first place?):

socket.on('data', function (d) {
    d = angular.fromJson(d);
    $scope.data.push(d);
    $scope.dtInstance.rerender();
});

Upvotes: 1

Related Questions