user3125693
user3125693

Reputation: 950

Error using Datatable with Angularjs

I'm trying to create a jQuery Datatable using Angularjs framework, using the 2nd answer in this example . As soon as the ng-repeat is done loading the table, I will initialize the DataTable().

What happens is the arrows, filters, and search bar show up, but for some reason, the arrows don't sort if you click them. They toggle between up and down, but do not sort. The search box also searches by header name when I want it to be for the actual values in the rows.

The table's "itms" are populated when a button is clicked and HTTP response is received so .DataTable() is not called until the whole table is rendered.

I have also tested with just a table where itms is hardcoded and it works perfectly. What am I missing?

JS:

angular.module('abcapp')
.directive('repeatDone', function() {
    return function(scope, element, attrs) {
        if (scope.$last) { // all are rendered
            $('#my-table').DataTable();
        }
    }
})

HTML:

<div ng-if="itms && itms.length > 0" class="row">
 <table id="my-table" class="table table-striped" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>a</th>
            <th>b</th>
            <th>c</th>
            <th>d</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>a</th>
            <th>b</th>
            <th>c</th>
            <th>d</th>
        </tr>
    </tfoot>
    <tbody>
      <tr ng-repeat="itm in itms track by $index" repeat-done>
        <td>{{itm.a}}</td>
        <td>{{itm.b}}</td>
        <td>{{itm.c}}</td>
        <td>{{itm.d}}</td>
      </tr>
    </tbody>
  </table>
</div>

Upvotes: 0

Views: 688

Answers (2)

user3125693
user3125693

Reputation: 950

I put the DataTable() call in a function wrapper and it worked. I think the timeout wasnt being called and the function inside the timeout was being called. I tried to specify $(...).DataTable without parenthesis but there was a angular error so this was my solution.

Running into another issue though... Whenever the table gets updated after the first time it's populated, the elements don't change.

angular.module('...')
.directive('repeatDone', function($timeout) {
    return function(scope, element, attrs) {
        function initWrapper(){
            $('...').DataTable();
        }
        if (scope.$last) {
            $timeout(initWrapper,200);
        }
    }
})

Upvotes: 0

jtsnr
jtsnr

Reputation: 1210

Wrap the jQuery call in $timeout:

  .directive('repeatDone', function($timeout) {
    return function(scope, element, attrs) {
      if (scope.$last) { // all are rendered
        $timeout(function() {
          $('#my-table').DataTable();
        });
      }
    }
  })

Upvotes: 1

Related Questions