1

I am trying to build a filtering system for a table in AngularJS.

I have a list of products which are each tied to a system. I want to be able to have all systems listed in a select, and filter the products by the selected system.

This works great except for choosing the empty select option, which filters out all systems.

Here is my example code:

The controller:

function Controller($scope) {
$scope.products = [
    {id: 1, system_id: 1, name: 'Product 1'},
    {id: 2, system_id: 1, name: 'Product 2'},
    {id: 3, system_id: 2, name: 'Product 3'}
];   

$scope.systems = [
    {id: 1, name: 'System 1'},
    {id: 2, name: 'System 2'},
    {id: 3, name: 'System 3'}
];  

}

and the HTML:

<div ng-app ng-controller="Controller">

System: <select ng-model="filter.system_id" ng-options="system.id as system.name for system in systems">
            <option value="">All Systems</option>
        </select>

<ul>
<li ng-repeat="product in products | filter: filter : true">
    {{ product.name }}
    </li>
</ul>
</div>

Here is a working example:

http://jsfiddle.net/9yk7a6v3/

My end goal is to have multiple filters, where filter is the filtering object with each property tied to a separate select.

I am guessing that the problem is that the empty option is an empty string which is causing false on equality because of the strict option, but is there a way to make it behave correctly in this siutation?

1 Answer 1

0
var app = angular.module('myApp',['myFilters']);

angular.module('myFilters', []).
filter('customFilter', function () {
    return function (products,filter) {
        var results = [];
        console.log(filter);
        if(!filter.system_id) {
            return products;
        }
        angular.forEach(products, function(product) {
            if(product.system_id === filter.system_id) {
                results.push(product);
            }
        });
        return results;
    };
});


   <li ng-repeat="product in products | customFilter: filter">
        {{ product.name }}
        </li>
    </ul>

we can use a custom filter to accomplish this

see in action

http://jsfiddle.net/xujihui1985/9yk7a6v3/2/

Sign up to request clarification or add additional context in comments.

1 Comment

Gotcha, I figured I would probably need to go down the custom filter route. I just figured I was so close to doing it the simple way I wasn't sure if there was a hack to get it working. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.