在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)
   })

demo -> http:/plnkr.coeditD72WPqkE3g2UgJTg。

记得注入 $compile 到您的控制器,例如,请参见 在angularjs中使用$compile. (糟糕的google甚至不屑于修复他们的文档中的错误,所以。https:/docs.angularjs.orgapingservice。$compile不起作用)。)

注意: 你也可以使用静态的 <table> 加价

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

然后AngularJS将连接 $scope.runmeng-click只有当你需要在DataTables插入的动态内容中进行额外的绑定时,才需要一个 $compile 是需要的。

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