【问题标题】:how to get the search box value in angular datatable?如何获取角度数据表中的搜索框值?
【发布时间】:2016-04-23 23:54:46
【问题描述】:

我使用的是angular datatable plugin,我想获取生成的数据表附带的搜索框的值。 Angular 数据表有几个 options 来制作数据表,但它们中的任何一个都允许我指定属性或我可以查看的内容以获取特定值。

由于我需要获取数据表的输入搜索的值,所以我找不到实现目的的方法。

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

【问题讨论】:

    标签: javascript angularjs search angular-datatables


    【解决方案1】:

    不幸的是,您不能$watch 搜索词/过滤器。 Angular dataTables 是使 jQuery dataTables runnable 在 Angular 中没有 DOM 冲突等的指令,但内部仍然像往常一样工作 - 以完全无角度的方式 :)

    但是,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

    【讨论】:

    • 很好的答案!非常感谢!
    【解决方案2】:

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

    要更新它,请确保您:

    有一个 dtInstance 和一个 dtOptions 对象:

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

    您将回调绑定到 dtOptions 中的“绘制”事件:

    this.dtOptions = { drawCallback: this.myCallbackFunction }
    

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

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

    【讨论】:

    • 我喜欢这个答案,因为它不需要 jquery
    猜你喜欢
    • 1970-01-01
    • 2022-10-14
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-29
    相关资源
    最近更新 更多