Question

I would like to filter an employee object array using $filter('filter') to filter the results based on an employee's first name field ONLY that can be selected from the drop down/select. Notes that I do NOT want to use the "| filter:" in the ng-repeat".

The difficulty is that the name field is a property of another field called 'details', so I can't details.name like the code below because it will error.

$scope.filteredEmployees = $filter('filter')(employees, {details.name: selectedName }); 

See below for structure of the employee array object.

How can I tell it to filter the records based on details.name field using $filter('filter')?

Thank you in advance for your help!

Here is the code:

Var selectedName = “An”;
$scope.filteredEmployees = $filter('filter')(employees, {**details.name:** selectedName });
Var employees  = [
      {
        Date: 01/01/2012
        details: {
          name: ‘An’,
      age: 25

        }
      },
      {
        Date: 01/01/2012
        details: {
          name: ‘'Bill',
      age: 20

        }
            }];

    //Here is 
    <select ng-model="selectedName" ng-options="e for e in employees" data-ng-show="employees.length > 0" ng-change="filterEmployees">
        <option value="">All Employees</option>
    </select><br>

    function filterEmployees()  {
        $scope.filteredEmployees = $filter('filter')(employees, "Joe");
    };
Was it helpful?

Solution

The expression can be a map of property-to-filters: where each property in the object maps to a corresponding property within the result set.

$filter('filter')(employees, {name:"Joe"});

Live Demo


Using A Custom Function

If your data is more complex, and you need more advanced filtering, then you can simply pass in a custom predicate function to evaluate whether or not an item should be filtered.

The input of the function takes each item of the array as an argument, and is expected to return false if the item should be excluded from the result set.

var people = [{date:new Date(), details:{
    name: 'Josh',
    age: 32
}}, {date:new Date(), details:{
    name: 'Jonny',
    age: 34
}}, {date:new Date(), details:{
    name: 'Blake',
    age: 28
}}, {date:new Date(), details:{
    name: 'David',
    age: 35
}}];

$scope.filteredPeople = $filter('filter')(people, function(person){
    return /^Jo.*/g.test(person.details.name);
});

Live Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top