0

I have an angular directive with the following template code for a table placeholder:

<table class="table table-striped table-bordered table-hover" id="testTableId">
    <thead>
        <tr>
            <th ng-repeat="column in columns">{{columns}}</th>
        </tr>
    </thead>
</table>

I'm trying to load the table data from within a controller within the directive.

var table = $('#testTableId').DataTable({
                responsive: true,
                serverSide: true,
                ajax: {
                    url: myUrl,
                    dataSrc: ''
                },
                fnServerData: function (sSource, aoData, fnCallback, oSettings) 
                {
                    oSettings.jqXHR = $.ajax({
                        url: myUrl,
                        success: function (json, status, xhr) {
                            //Do stuff
                        }
                    });
                }    
            });

The data loads in the table but I have the following error in the console:

TypeError: Cannot read property 'childNodes' of undefined

My table headers are gone and if I inspect the HTML I can see my ng-repeat directive has been commented out.

Help please?

Added:

If I render the table beforehand outside the directive. Loading the data into the table works. Looks like it's some sort of timing issue.

Sun
  • 4,458
  • 14
  • 66
  • 108

2 Answers2

1

I used the solution from this question to fix the problem:

enter link description here

It seemed to be a problem with the repeat not finishing before loading the data.

Sun
  • 4,458
  • 14
  • 66
  • 108
0

The problem here is that your selector $('#testTableId') doesn't find the element, causing that var table = undefined. It seems that stops the execution of the rest of the code. My suggestion is to avoid to use jQuery for this task. You could load your data first and then handle it using HTML.

JS

app.controller('MainCtrl', function($scope) {
    $scope.data;
    $scope.columns = ['something', 'somethingElse'];

    activate();

    function activate() {
      getData();
    }

    function getData() {
      //Do your request to get the data
      yourRequest().then(function(response) {
        $scope.data = response;
      }); 
    }
});

HTML

<table class="table table-striped table-bordered table-hover" id="testTableId">
    <thead>
        <tr>
            <td ng-repeat="column in columns">{{columns}}</td>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="row in data></tr>
    </tbody>
</table>