Reputation: 2711
I´ve been stuck for some time on a sortingfeature using angular.
What I hope to achieve is the ability to filter friends
by clicking one of the three buttons with ages.
Ex:
App starts with all friends showing.
I click the button with 20
and only friends with age 20 shows.
I click 20 again -> all friends show.
I have code similar to this:
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
};
});
And the view:
<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>
Upvotes: 0
Views: 1702
Reputation: 691695
So, you first need to filter:
<tr ng-repeat="x in friends | filter:theFilter">
So, you need theFilter
to exist in the scope, and by default, it shouldn't filter anything:
$scope.theFilter = {};
Now, when filterByAge()
is called, it should modify the filter so that it filters by the given age:
$scope.filterByAge = function(age) {
$scope.theFilter.age = age;
};
Except you want that, if the button is clicked again, and the filter already filters by that age, then the filtering is cancelled. So you want
$scope.filterByAge = function(age) {
if ($scope.theFilter.age === age) {
$scope.theFilter = {};
}
else {
$scope.theFilter.age = age;
}
};
Here's your plunkr doing it: http://plnkr.co/edit/atbvQ6lbUJmyq9ZJfmCj?p=preview
Upvotes: 1