2

I am trying to add a button to the heading of a column in angular-datatables, which when clicked will run a function. I have tried doing something like this.

DTColumnBuilder.newColumn('name').withTitle(function() {
    return '<span>Name</span><button ng-click="runme()">Click me</button>'
})

In the same controller, runme() function is defined as:

$scope.runme = function() {
    console.log('clicked');
}

But this is not triggered, it only sort the column data, no matter where i clicked on entire header section.

davidkonrad
  • 83,997
  • 17
  • 205
  • 265
Michael
  • 123
  • 1
  • 8

1 Answers1

2

When you are using this approach you'll need to $compile the content of the <thead> (and anything else injected by DataTables you would like AngularJS to be aware of).

A good place to invoke $compile is in the initComplete callback :

$scope.dtOptions = DTOptionsBuilder.newOptions()
  .withOption('initComplete', function() {
      $compile(angular.element('thead').contents())($scope)
   })

demo -> http://plnkr.co/edit/D72WPqkE3g2UgJTg

Remember to inject $compile to your controller, see for example Working with $compile in angularjs. (Lousy google does not even bother to fix the errors in their docs, so https://docs.angularjs.org/api/ng/service/$compile does not work).

Note: You could also go with static <table> markup

<table>
  <thead>
    <tr>
      <th><span>Name</span><button ng-click="runme()">Click me</button></th>
    </tr>
  </thead>
  <tbody></tbody>
</table> 

Then AngularJS will connect $scope.runme to the ng-click, and only if you need additional bindings in the dynamic content inserted by DataTables, a $compile is needed.

davidkonrad
  • 83,997
  • 17
  • 205
  • 265