Convert-Inline ng-重复过滤器到自定义过滤器 - angularjs
问题描述:
<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
}]
})
我想声明自定义过滤器来过滤online和productType并从角度html模板调用自定义过滤器。上面的内联过滤器工作正常,但我期待将内联过滤器转换为自定义过滤器。其实想要从html页面移动过滤器功能。 注意:productType可以为null。Convert-Inline ng-重复过滤器到自定义过滤器 - angularjs
答
您可以定义自定义过滤器下面的方式
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>
谢谢你,但有一个问题,它即时通讯无法弄清楚当我将此过滤器集成到现有的角度js模块中时。如果我有第二个参数不是空的angular.module(“myApp”,'服务'),过滤不起作用 – user2057006
错误:[$注射器:unpr]未知提供者:productFilterFilterProvider user2057006
浏览器问题我猜。现在它按预期工作。做得好。谢谢。 :) – user2057006