本文介绍了如何筛选使用几个环节在AngularJS列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经持续了大量的教程就如何过滤列表,找不到我简单的用例的例子。

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.

我有几个按钮,如

<a href="#" id="filter-by-name">Name</a>
<a href="#" id="filter-by-age">Age</a>
<a href="#" id="filter-by-height">Height</a>

变种人= {...} 对象,我展示它像

<div ng-repeat="person in persons">
  {{person.name...}}
</div>

如何创建过滤器所以每次我都会点击列表将被过滤掉其中一个按钮?

我曾尝试加入 NG-重复=人的人|过滤器:filterPersons
并在剧本一边写的:

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;
}

但是这是唯一一个用例(我怎么能由另一个名称进行筛选?) - 换句话说? - 如何连接的链接过滤器

推荐答案

您可以将过滤器绑定到范围变量您使用任何其他的事情要做。因此,所有你需要的是在拨过滤器设置范围,当用户点击其绑定到 NG-重复过滤参数。参见:

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'}];
}

请注意, myFilter 当用户点击过滤器发生了变化,而且它绑定到 NG-重复过滤器。 。你也可以创建一个新的过滤器,但这个解决方案是更好的。

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列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 23:17