我已经在使用角度的分类功能上停留了一段时间。
我希望实现的是通过单击三个按钮之一来过滤friends
的能力。
例:
应用程序从所有朋友展示开始。
我点击了20
按钮,只显示了20岁的朋友。
我再次点击20 - >所有的朋友都表现出来。
我的代码类似于:
http://plnkr.co/edit/iU2XjDsV2K8wThxdlZ8w?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.friends = [
{name:'John', age:20, gender:'boy'},
{name:'Jessie', age:30, gender:'girl'},
{name:'Johanna', age:40, gender:'girl'},
{name:'Joy', age:20, gender:'girl'},
{name:'Mary', age:30, gender:'girl'},
{name:'Peter', age:40, gender:'boy'},
{name:'Sebastian', age:20, gender:'boy'},
{name:'Erika', age:30, gender:'girl'},
{name:'Patrick', age:40, gender:'boy'},
{name:'Samantha', age:20, gender:'girl'}
];
$scope.filterByAge = function(age) {
// filter based on the age passed to this method
// unfilter (show all friends) if 'age' already
//is the same as the argument
};
});
观点:
<body ng-controller="MainCtrl">
<p>Sort by age</p>
<button ng-click="filterByAge('20')">20</button>
<button ng-click="filterByAge('30')">30</button>
<button ng-click="filterByAge('40')">40</button>
<table>
<tbody>
<tr ng-repeat="x in friends">
<td>{{ x.name }}</td>
<td>{{ x.age }}</td>
</tr>
</tbody>
</table>
</body>
答案 0 :(得分:1)
所以,首先需要过滤:
<tr ng-repeat="x in friends | filter:theFilter">
因此,您需要theFilter
存在于范围内,默认情况下,它不应过滤任何内容:
$scope.theFilter = {};
现在,当调用filterByAge()
时,它应该修改过滤器,以便按给定年龄过滤:
$scope.filterByAge = function(age) {
$scope.theFilter.age = age;
};
除非您需要,否则如果再次单击该按钮,并且过滤器已按该年龄过滤,则会取消过滤。所以你想要
$scope.filterByAge = function(age) {
if ($scope.theFilter.age === age) {
$scope.theFilter = {};
}
else {
$scope.theFilter.age = age;
}
};