如何获取 angular 数据表中的搜索框值?

how to get the search box value in angular datatable?

我正在使用 angular datatable plugin, and I want to get the value of the search box that comes with the generated datatable. Angular datatable has a few options 制作数据表,但它们中的任何一个都允许我指定属性或我可以为了获得特定值而观看的东西。

由于需要获取datatable的input search的值,所以找不到方法来完成我的目的。

那么,如何获取 angular 数据表中的搜索框值?

不幸的是,您无法 $watch 搜索词/过滤器。 Angular dataTables 是使 jQuery dataTables runnable in angular 没有 DOM 冲突等的指令,但内部仍然一如既往地工作 -以完全 none-angular 的方式:)

然而,dataTables在每次执行搜索/过滤时广播一个search(.dt)事件,然后你可以直接从DOM中提取搜索的值:

angular.element('body').on('search.dt', function() {  
   var searchTerm = document.querySelector('.dataTables_filter input').value;
   console.log('dataTables search : ' + searchTerm); 
})

这当然是最简单的类似jQuery的方法。您可能在页面上有多个数据表,并希望为每次搜索提取更详细的信息,然后您可以在 angular 应用程序中使用:

angular.element('body').on('search.dt', function(e, api) {  
   if (!$scope.$$phase) { 
      $scope.$apply(function() {
         $scope.searchTerm = api.oPreviousSearch;
         $scope.searchTerm.table = e.target.id;
      })   
   }  
})

$apply 以便从事件处理程序内部更新 $scopeoPreviousSearch 实际上是当前搜索,所以上面在

的形式上产生了 $watch'able searchTerm
{
  "bCaseInsensitive": true,
  "sSearch": "test",
  "bRegex": false,
  "bSmart": true,
  "_hungarianMap": {
    "caseInsensitive": "bCaseInsensitive",
    "search": "sSearch",
    "regex": "bRegex",
    "smart": "bSmart"
  },
  "table": "tableId"
}

查看演示 -> http://plnkr.co/edit/E5Tr7FrLRIVTtguQHFx9?p=preview

您可以使用 search() 函数(不带参数)获取实际搜索值。

要更新它,请确保您:

有一个 dtInstance 和一个 dtOptions 对象:

<table datatable dt-instance="vm.dtInstance" dt-options="vm.dtOptions">

您在 dtOptions 中将回调绑定到 "draw" 事件:

this.dtOptions = { drawCallback: this.myCallbackFunction }

然后在你的函数中你可以这样做:

this.myCallbackFunction = () => {
   let mySearchValue = this.dtInstance.DataTable.search() 
}