Can ANYBODY make DataTables be happy on Angular 2?

Can ANYBODY make DataTables be happy on Angular 2?

drullodrullo Posts: 2Questions: 0Answers: 0
edited January 2017 in Free community support

Here's the bottom line... you can get DataTables to work in Angular 2 just fine - as long as your data is static. But if you have a real-world application where you call an Angular service to dynamically fetch your data when your component is initialized, it breaks DataTables. The table displays correctly initially. But as soon as you try to sort a column or search, all of the data disappears.

I was able to implement a really ugly work-around (hack) by delaying the application of the DataTable() call via a setTimeout - essentially giving Angular time to manipulate the DOM before DataTables does. But this is undesirable for a number of reasons.

I was hoping that Angular-DataTables (a bridge between the two) would solve the problem. And while I do like some things about it, this particular problem does not go away.

I understand that this is not an Angular 2 support forum. But given the popularity of that platform, I would think that the DataTables team would have some interest in making it work properly on it.

Replies

  • allanallan Posts: 63,535Questions: 1Answers: 10,475 Site admin

    I do have interest in it, but unfortunately haven't yet had time. When you say the "DataTables team", its just me :smile:. I'm not yet sure when I'll be able to look into this.

    Allan

  • drullodrullo Posts: 2Questions: 0Answers: 0

    Allan thank you for the response. I did not realize that this was a one-man effort. Thanks for your efforts!

  • JacrysJacrys Posts: 1Questions: 0Answers: 0
    edited February 2017

    So I found this hunting around Stack Overflow and it works, at least with Angular 1 (I haven't learned Angular2 yet.). It uses a custom directive then an empty $timeout to delay the call to datatables init until your model has been populated.

    JS:

    var app = angular.module("JobTracker", [])
      
      .directive('tableInit',['$timeout', function($timeout) {
        return {
          link: function($scope, element, attrs) {
            $scope.$on('dataloaded', function() {
              $timeout(function () {
                $('#myTable').DataTable();
              }, 0, false);
            })
          }
        };
      }]);
    

    HTML:

    <table id="myTable" table-init class="display compact">`
    
    ...
    
    </table>
    

    EDIT:
    Here is the thread I found it on.

    Run jQuery code after AngularJS completes rendering HTML

This discussion has been closed.