Filter multiple repeated properties using AND operation in Angularjs application

I have the following array of json objects in my angularjs application.

$scope.clients = [ {  
  "code": "FREG",
  "name": "Feranget",
  "role": "employee" 
},
{  
  "code": "CRTE",
  "name": "Crenart",
  "role": "admin" 
},
{  
  "code": "DERT",
  "name": "Derta",
  "role": "admin" 
} ]

I have a search form where I can enter code in a text box to search in these clients based on code. So I applied a filter in ng repeat in a property codethat works fine.

<tbody ng-if="clientSearch.clientCode">
    <tr ng-repeat="client in clients | filter:{ code: clientSearch.clientCode }">
</tbody>

, name role clientSearch.clientName clientSearch.clieRole. clientSearch.clientName name clientSearch.clieRole role AND , .. code role , code role, name , . name, code role name. , AND.

<tbody ng-if="clientSearch.clientCode">, , clientCode , . clientSearch.clientName, clientSearch.clieRole clientSearch.clientCode. <tbody ng-if="clientSearch">, ,

, :

$scope.clientSearch = {               clientCode: '',                : '',               clientRole: ''       }

- genralized .

+4
3

<tbody ng-if="(clientSearch.clientCode !=null && clientSearch.clientCode !='') || (clientSearch.clientName !=null && clientSearch.clientName !='') || (clientSearch.clientRole !=null && clientSearch.clientRole !='')">
    <tr ng-repeat="client in clients | filter:{ code: clientSearch.clientCode, name: clientSearch.clientName}">
</tbody>

, AND.

. : http://plnkr.co/edit/kozaU39E74yqjZCpgDqM?p=preview

+1

,

app.filter('filterbyNameRoleCode', function(){
      return function(items,name,role,code){
         var filtered = [];

         for (var i = 0; i < items.length; i++) {

         if (itmes[i].name.indexof(name)> -1 && itmes[i].role.indexof(role)> -1 && itmes[i].code.indexof(code)> -1 ) {
          filtered.push(items[i]);
        };
      };
    } 
    return filtered;

});

<tbody ng-if="show(clientSearch)">
<tr ng-repeat="client in clients | filterbyNameRoleCode:clientSearch.clientName:clientSearch.clientRole:clientSearch.clientCode }">
</tbody>
+1

I think the most elegant way to do this (without using multiple filters or conditions in your HTML) would be to create a custom filter :

yourApp.filter('customFilter', function() {
  return function (input, obj) {
    if (/* test that input complies with your conditions obj */) {
      return true;
    }
    return false;
  };
});

HTML:

<tr ng-repeat="client in clients | customFilter:clientSearch">
0
source

Source: https://habr.com/ru/post/1618780/


All Articles