问题描述
`在我的代码iam中,使用自定义过滤器过滤性别(男,女).但是在我的输出中,当我单击雄性"时,它不会过滤,但是当我单击雌性"时,它将显示仅由雌性组成的已过滤输出.我不知道我的错误在哪里.
`In my code iam using custom filter for filtering gender(male,female).but in my output when i click male it does not filter,but when i click female it shows filtered output consisting of only females. I dont know where is my mistake.
app.filter('myFilter', function () {
return function (items, filterby) {
var filtered = [];
var filtermatch = new RegExp(filterby, 'i');
for (var i = 0; i < items.length; i++) {
if (filtermatch.test(items[i].gender) {
filtered.push(items[i]);
}
}
return filtered;
};
});
<ul id="result">
<li ng-repeat="x in details | myFilter:filterby">
<div>Name: {{x.name }}</div>
<div>Address: {{x.address}}</div>
<div>Gender: {{x.gender }}</div>
<div>Country: {{x.country}}</div>
<div>Agree: {{x.agree }}</div>
</li>
</ul>
这是我的男性和女性单选按钮的代码
And this is my code for radio buttons male and female
<div class="form-group">
<label for="filterby" class="control-label col-xs-2">Filter By Gender</label>
<div class="radio">
<label>
<input type="radio" name="options" id="options2"
ng-model="filterby" value="female">
<label for="gender" class="control-label col-xs-2">Female</label>
</label>
<label>
<input type="radio" name="options" id="options2"
ng-model="filterby" value="male">
<label for="gender" class="control-label col-xs-2">male</label>
</label>
</div>
</div>
推荐答案
除了您没有使用 sort
参数这一事实外,如果您想将多个参数传递给过滤器,也可以将它们分开与:
.
Apart from the fact that you are not using the sort
argument, if you want to pass multiple parameters to a filter you separate them with :
.
ng-repeat="x in details | myFilter:prop1:prop2">
这将在返回的数组上调用 myFilter(details,prop1,prop2)
和 ngRepeat
.
This will call myFilter(details, prop1, prop2)
and ngRepeat
over the returned array.
这篇关于如何在angularjs中使用自定义过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!