angularjsngtable

angularjs - ngTable - issue with dynamic filter in controller


I want to create a filter for my ngTable.

In the controller at the root (not in a function) I do :

$scope.filters = {
   nomSociete: 'test'
}

then

$scope.tableParamsContacts.reload();
$scope.tableParamsContacts = new ngTableParams({
           page: 1,            // show first page
           count: 10,
           filter : $scope.filters,
           sorting: {
               nom:'asc',
               prenom:'asc'
           }
       }, {
           total: dataContact.length, // length of data
           getData: function($defer, params) {
               // use build-in angular filter
               var filteredData = params.filter() ?
                   $filter('filter')(dataContact, params.filter()) :
                   data;
               var orderedData = params.sorting() ?
                   $filter('orderBy')(filteredData, params.orderBy()) :
                   dataContact;

               params.total(orderedData.length); // set total for recalc pagination
               if(params.total() < (params.page() -1) * params.count()){
                   params.page(1);
               }
               $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
           }
       });

It works

But if I place

$scope.filters = {
   nomSociete: 'test'
} 

in a function in my controller:

vm.onClientSelect = function(affaire){
   $scope.filters = {
      nomSociete: 'test'
   }
   $scope.tableParamsContacts.reload();
}

It doesn't work, the value of the filter doesn't appear in the ng table, and the ng table gets empty.

I don't understand why.


Solution

  • Change the filter directly from within your ngTableParams like this:

     $scope.filters = {
       nomSociete: 'test'
     } 
     $scope.tableParamsContacts.filter($scope.filters);
     $scope.tableParamsContacts.reload();