AngularJS filter by select with empty options

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?

Answers:

Answer
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/

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.