我正在尝试创建一个类似网站的商店,其中有产品的过滤选项。我需要过滤器才能选择多个选项,并显示包含选择的所有项目。例如,选择食物复选框,对于家具,显示所有类型的食物和家具产品。如果未选择这些,则显示所有产品类型。
我有一个半工作的JSFiddle。它会过滤一个复选框,但只要选择了第二个复选框,它就不会显示任何结果。 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>
我看过其他类似的问题,答案就像这样:How to filter multiple values (OR operation) in angularJS with checkbox
这种方法对我不起作用。我需要开始展示所有产品,并过滤掉未选择的产品。
答案 0 :(得分:1)
分叉小提琴:http://jsfiddle.net/85dobcum/
这应该适合你:
<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 }
}
}