0

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>

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.