Reputation: 25
I am trying to create a shop like site where there is a filter option for products. I need the filter to be able to have more than one option selected, and show all the items that contain the selections. Example, checkbox for food is selected, and for furniture, show all products of type food and furniture. If none of these are selected, then show all product types.
I have a JSFiddle that is half working. It will filter down a checkbox, but as soon as a second one is selected, it shows no results. http://jsfiddle.net/ellenburgweb/om58sdbd/8/
<div ng-app ng-controller="Main">
<input type='checkbox' ng-model='filterFood' ng-true-value="Food" ng-false-value="" />Food
<br />
<input type='checkbox' ng-model='filterFurniture' ng-true-value="Furniture" ng-false-value="" />Furniture
<br />
<input type='checkbox' ng-model='filterFences' ng-true-value="Fences" ng-false-value="" />Fences
<br />
<hr />
<div ng-repeat="product in products | filter:search | filter:filterFood | filter:filterFurniture | filter:filterFences">
{{product.name}} | {{product.type}}</div>
</div>
<script>
function Main($scope){
$scope.products = [{name: 'Product One', type: 'Food'},
{name: 'Product Two', type: 'Furniture'},
{name: 'Product Three', type: 'Fences'},
{name: 'Product Four', type: 'Food'},
{name: 'Product Five', type: 'Furniture'},
{name: 'Product Six', type: 'Fences'}];
}
</script>
I have seen other similar questions, and the answers to them are much like this one: How to filter multiple values (OR operation) in angularJS with checkbox
That method will not work for me. I need all the products to be showing to begin with, and filter out what is not selected.
Upvotes: 0
Views: 26
Reputation: 5176
Forked fiddle here: http://jsfiddle.net/85dobcum/
This should do it for you:
<div ng-app ng-controller="Main">
<input type='checkbox' ng-model='Food' ng-true-value="Food" ng-false-value="" />Food
<br />
<input type='checkbox' ng-model='Furniture' ng-true-value="Furniture" ng-false-value="" />Furniture
<br />
<input type='checkbox' ng-model='Fences' ng-true-value="Fences" ng-false-value="" />Fences
<br />
<hr />
<div ng-repeat="product in products | filter:search | filter: productType">
{{product.name}} | {{product.type}}
</div>
</div>
function Main($scope){
$scope.products = [{name: 'Product One', type: 'Food'},
{name: 'Product Two', type: 'Furniture'},
{name: 'Product Three', type: 'Fences'},
{name: 'Product Four', type: 'Food'},
{name: 'Product Five', type: 'Furniture'},
{name: 'Product Six', type: 'Fences'}];
$scope.productType = function(product) {
var filters = []
filters.push($scope.Food)
filters.push($scope.Furniture)
filters.push($scope.Fences)
if (filters.toString().length <=4) {return true}
else {return filters.indexOf(product.type)>-1 }
}
}
Upvotes: 1