向AngularJS中的DataTables列标题添加操作按钮

问题描述 投票:1回答:1

我正在尝试向angular-datatables中的列标题添加按钮,单击该按钮将运行一个功能。我已经尝试过做这样的事情。

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

在同一控制器中,runme()功能定义为:

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

但是不会触发,它仅对列数据进行排序,无论我单击整个标题部分的位置如何。

angularjs datatables angular-datatables
1个回答
1
投票

使用这种方法时,您需要$compile <thead>的内容(以及您希望AngularJS注意的其他所有由DataTables注入的内容)。

调用$compile的好地方在initComplete回调中:

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

演示-> http://plnkr.co/edit/D72WPqkE3g2UgJTg

请记住将$compile注入您的控制器,例如参见Working with $compile in angularjs。 (Lousy google甚至不费心去解决文档中的错误,因此https://docs.angularjs.org/api/ng/service/ $ compile不起作用。

注意:您也可以使用静态<table>标记

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

然后AngularJS将$scope.runme连接到ng-click,并且仅当您需要在DataTables插入的动态内容中需要其他绑定时,才需要$compile

© www.soinside.com 2019 - 2024. All rights reserved.