Search code examples
javascriptangularjssearchangular-datatables

how to get the search box value in angular datatable?


I'm using 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 to make a datatable, but any of them allow me specify attributes or something that I could watch with the purpose to get a particular value.

Since I need to get the value of the input search of the datatable, I can't find a way to accomplish my purpose.

So, how can I get the search box value in angular datatable?


Solution

  • Unfortunetaly you cannot $watch the search term / filter. Angular dataTables is directives that makes jQuery dataTables runnable in angular without DOM conflicts etc, but the internals still works as always - in a completely none-angular way :)

    However, dataTables broadcasts a search(.dt) event each time a search / filter is performed, and then you can extract the value of the search directly from the DOM :

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

    This is of course the most simple jQuery-like approach. You may have more than one dataTable on the page and want to extract more detailed information for each search, you then can use in your angular app :

    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 in order to update $scope from inside the event handler. oPreviousSearch is in fact the current search, so the above produces a $watch'able searchTerm on the form

    {
      "bCaseInsensitive": true,
      "sSearch": "test",
      "bRegex": false,
      "bSmart": true,
      "_hungarianMap": {
        "caseInsensitive": "bCaseInsensitive",
        "search": "sSearch",
        "regex": "bRegex",
        "smart": "bSmart"
      },
      "table": "tableId"
    }
    

    see demo -> http://plnkr.co/edit/E5Tr7FrLRIVTtguQHFx9?p=preview