【问题标题】:How to invoke custom filter manually?如何手动调用自定义过滤器?
【发布时间】:2016-10-08 20:06:25
【问题描述】:
<div "ng-repeat="phone in phoneList| filter:filterPrice">
//custome filter
$scope.filterPrice = function (phone) {
return (phone.price > MIN_VAL && phone.price < MAX_VAL);};
MAX_VAL 和 MIN_VAL 是我从输入中获得的输入值,我必须在 MAX_VAL 或 MIN_VAL 更改时更新 phoneList。
我收到值发生更改的事件,但如何在列表中更新?
【问题讨论】:
标签:
javascript
angularjs
angularjs-scope
angularjs-ng-repeat
ng-repeat
【解决方案1】:
您可以使用filter 对这个经过的用户输入minValue 和maxValue 进行过滤。
<li ng-repeat="phone in phoneList | filterPrice:maxValue:minValue">
{{ phone }}
</li>
发送您要过滤的列表作为第一个参数,然后根据您传递的顺序从 HTML 模板发送 minValue、maxValue。过滤后,您可以返回一个新列表。
app.filter('filterPrice', function() {
return function(phoneList, maxValue, minValue) {
// You can refine this logic
if(!maxValue && !minValue)
return phoneList;
var filtered = [];
filtered = phoneList.filter(function(obj){
if(maxValue && !minValue){
return obj.price <= maxValue;
} else if(!maxValue && minValue){
return obj.price >= minValue;
}
return (obj.price >= minValue && obj.price <= maxValue )
})
return filtered;
};
});
Plunker
【解决方案2】:
使用此格式应用过滤器:
app.filter('myFilter', function() {
return function(input, optional1, optional2) {
var output;
// Do filter work here
return output;
}
});