Search code examples
javascriptangularjsfilterangularjs-ng-repeat

Filter a list with ng-repeat


I have a list as follows

$scope.arrayList = [
   {"name": "test1", "age":2},
   {"name": "test2", "age":4},
   {"name": "test3", "age":2},
   {"name": "test1", "age":4}
]

Initially when the program run whole list should be displayed to the user. then through another dropdown user should be able to select age. then according to the selected age the list should be filtered and display only the relevant data only. Please find the below code

HTML

<div ng-repeat="array in arrayList | filter:filterByAge">{{array}}</div>

<select ng-model="selAge">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

controller

$scope.filterByAge = function(selectedAgeVal)
{
    if($scope.arrayList.age ==selectedAgeVal)
    {
        $scope.arrayList;
        return true;
    }
    else
    {
        return false;
    } 
}

But this code is not working correctly. Initial load of arrayList is not even working properly. Can anybody help me to figure out how to filter within ng-repeat? Thanks in advance


Solution

  • The problem with your custom filter is that, parameter of your custom filter function is a row from your list not selected age value. So changing your custom filter with the following should solve the issue.

      $scope.filterByAge = function(row)
      {
          if(row.age == $scope.selAge)
          {
              return true;
          }
          else
          {
              return false;
          } 
      }
    

    In order to display whole list on start you can add a null check.

     $scope.filterByAge = function(row)
      {
          if($scope.selAge != undefined){
              if(row.age == $scope.selAge)
              {
                  return true;
              }
              else
              {
                  return false;
              } 
          }
          else{
            return true;
          }
      } 
    

    Demo