问题描述
我已经阅读了很多关于如何过滤列表的教程,但找不到适合我的简单用例的示例.
我有几个按钮,例如
名称<a href="#" id="filter-by-age">年龄</a><a href="#" id="filter-by-height">高度</a>
我有 var people = {...}
对象,我像这样显示它
{{人名...}}
如何创建过滤器,以便每次单击其中一个按钮时都会过滤列表?
我尝试添加ng-repeat="person in people | filter:filterPersons"
并在脚本方面编写:
$scope.filterPersons(person){if (person.name == "John")归还人;}
但这只是一个用例(我如何用另一个名称过滤?) - 换句话说 - 如何将链接连接到过滤器?
您可以像处理任何其他事情一样将过滤器绑定到作用域变量.因此,您只需要在用户单击并将其绑定到 ng-repeat
过滤器参数时将适当的过滤器设置为范围.见:
<span ng-click="myFilter = {type: 1}">Type 1</span>|<span ng-click="myFilter = {type: 2}">Type 2</span>|<span ng-click="myFilter = null">无过滤器</span><ul ng-controller="测试"><li ng-repeat="person in people | filter:myFilter">{{person.name}}</li>
function Test($scope) {$scope.persons = [{type: 1, name: 'Caio'}, {type:2, name: 'Ary'}, {type:1, name: 'Camila'}];}
请注意,当用户单击过滤器时 myFilter
会更改,并且它绑定到 ng-repeat
过滤器.在这里小提琴.您也可以创建一个新过滤器,但此解决方案要好得多.
I have been going over a lot of tutorials on how to filter a list and can't find an example for my simple use-case.
I have several buttons such as
<a href="#" id="filter-by-name">Name</a>
<a href="#" id="filter-by-age">Age</a>
<a href="#" id="filter-by-height">Height</a>
I have var persons = {...}
object and I display it like
<div ng-repeat="person in persons">
{{person.name...}}
</div>
How do I create a filter so each time I will click on one of the buttons the list will be filtered ?
I have tried addingng-repeat="person in persons | filter:filterPersons"
and on the script side to write:
$scope.filterPersons(person){
if (person.name == "John")
return person;
}
but this is only one use-case (how can I filter by another name?) - in other words - How do I connect the links to the filter?
You can bind your filter to scope variables as you do with any other thing. So all you need is to set the appropriated filter to the scope when the user click and bind it to the ng-repeat
filter param. See:
<div ng-app>
<span ng-click="myFilter = {type: 1}">Type 1</span> |
<span ng-click="myFilter = {type: 2}">Type 2</span> |
<span ng-click="myFilter = null">No filter</span>
<ul ng-controller="Test">
<li ng-repeat="person in persons | filter:myFilter">{{person.name}}</li>
</ul>
</div>
function Test($scope) {
$scope.persons = [{type: 1, name: 'Caio'}, {type:2, name: 'Ary'}, {type:1, name: 'Camila'}];
}
Notice that the myFilter
is changed when the user clicks the filter, and that it's bound to the ng-repeat
filter. Fiddle here. You could also create a new filter, but this solution is far better.
这篇关于如何使用多个链接过滤 AngularJS 中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!