Search code examples
angularjsmulti-selectangular-filters

Angular Filter based on Multiselect-Dropdown


I use nya-bootstrap-select directive (http://nya.io/nya-bootstrap-select/) for a Multiselect-Dropdown ( Angular 1.5.8 ). Now I would like to filter a collection based on the selected options.

Example:

https://jsfiddle.net/mrtzdev/2z6xfo5w/18/

<ol id="dynamic-options" class="nya-bs-select" ng-model="model2" multiple >
  <li nya-bs-option="(key,value) in companyList" >
    <a>{{ value.name}}</a>
  </li>
</ol>

Filtered Collection:

<tbody>
        <tr ng-repeat="client in clients | filter:{ name: model1.name, company: { name: model2.name } } ">
            <td>{{$index + 1}}</td>
            <td><em>{{client.name}}</em>

            </td>
            <td>{{client.designation}}</td>
            <td>{{client.company.name}}</td>
        </tr>
    </tbody>

This obviously does not work for the multiselect. How can use a custom filter, to filter on multi-selected options ?


Solution

  • I modified your fiddle and make it work. This filter is not good in dynamic handling but it will allow you to filter your data by the exact filter attribute name.

    View

    <tr ng-repeat="client in clients | filter:{ name: model1.name} | inArrayExact : { myArray: model2, searchKey: 'name', filterKey: 'company' }">
        <td>{{$index + 1}}</td>
        <td><em>{{client.name}}</em>
    
        </td>
        <td>{{client.designation}}</td>
        <td>{{client.company.name}}</td>
    </tr>
    

    AngularJS custom filter

    App.filter('inArrayExact', function($filter){
        return function(list, arrayFilter, element){
            if((angular.isArray(arrayFilter.myArray) && arrayFilter.myArray.lenght > 0) &&  || angular.isObject(arrayFilter.myArray)){
                var itemsFound = {};
                angular.forEach(list, function (listItem, key) {
                  angular.forEach(arrayFilter.myArray, function (filterItem) {
                     if (angular.isDefined(filterItem[arrayFilter.searchKey]) 
                     && angular.isDefined(listItem[arrayFilter.filterKey])
                     && angular.isDefined(listItem[arrayFilter.filterKey][arrayFilter.searchKey])) {
                       if (angular.isUndefined(itemsFound[key]) 
                       && listItem[arrayFilter.filterKey][arrayFilter.searchKey] == filterItem[arrayFilter.searchKey]) {
                          itemsFound[key] = listItem;
                       }
                     }
                  });
                });
                return itemsFound;
            } else {
              return list;
            }
        };
    });