<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl as vm">
<form class="col2">
<label for="filter-online">
Filter by Online
</label>
<div class="select">
<select id="filter-online" ng-model="vm.online" class="form-control" ng-options="online for online in vm.onlines">
<option value="">All</option>
</select>
</div>
</form>
<form class="col2">
<label for="filter-productType">
Filter by Product Type
</label>
<div class="select">
<select id="filter-productType" ng-model="vm.productType" class="form-control" ng-options="productType for productType in vm.productTypes">
<option value="">All</option>
</select>
</div>
</form>
<table style="margin-top: 30px">
<tr ng-repeat="lim in vm.stockLimits | filter:{online:vm.online || undefined, productType: vm.productType || undefined}">
<td>{{lim.online}}</td>
<td>{{lim.productType}}</td>
</tr>
</table>
</div>
angular.module("myApp", [])
.controller("myCtrl", function($scope) {
var vm = this;
vm.onlines = ["Men", "Kids", "Ladies"];
vm.productTypes = ["Shirt", "Shoe", "Belt", "Top"];
vm.stockLimits = [{
id: 1,
online: "Men",
productType: "Shirt"
}, {
id: 2,
online: "Men",
productType: "Shoe"
}, {
id: 3,
online: "Kids",
productType: "Belt"
}, {
id: 4,
online: "Ladies",
productType: "Top"
},
{
id: 5,
online: "Kids",
productType: null
}]
})
我想声明自定义过滤器以过滤在线和productType,并从角度html模板调用自定义过滤器。上面的内联过滤器工作正常,但我期待将内联过滤器转换为自定义过滤器。实际上想从html页面移动过滤器功能。 注意:productType可以为null。
答案 0 :(得分:1)
您可以按照
的方式定义自定义过滤器angular.module("myApp").filter('productFilter', function() {
return function(items, filterOptions) {
if (!items) {
return []
}
return items.filter(function(item) {
var isOnlinePassed = filterOptions.online ? (item.online === filterOptions.online) : true,
isProductTypePassed = filterOptions.productType ? (item.productType === filterOptions.productType) : true;
return isOnlinePassed && isProductTypePassed;
})
}
})
然后在模板中使用过滤器,如:
<table style="margin-top: 30px">
<tr ng-repeat="lim in vm.stockLimits | productFilter:{online:vm.online , productType: vm.productType}">
<td>{{lim.online}}</td>
<td>{{lim.productType}}</td>
</tr>
</table>