Friday, July 17, 2015

AngularJS ng-options Filter by Custom Function

In AngularJS when you are using ng-options, you can filter out the options by calling  a custom function you have in the controller.

Let’s say you have following set of employees and when you display all these employees inside HTML select using ng-options, you can see all the employees in a dropdown.
$scope.employees = [
    {
        name: "Jaliya Udagedara",
        department: "VS",
    },
    {
        name: "John Smith",
        department: "VS",
    },
    {
        name: "Jane Smith",
        department: "SQL",
    }
];
image
Result without Filter
And now let's say, you only need employees whose department is “VS”.

For that I am filtering the employees where department equals “VS” and that’s by calling a custom function. (here for this simple requirement I really don’t need to write a custom filter function, I can supply the filter even inline, but for the demonstration purposes, let’s call a custom function.)
<select ng-options="employee.name for employee in employees | filter:filterEmployeesByDepartment()"
        ng-model="selectedEmployee">
</select>
So here is the filter function inside the controller.
$scope.filterEmployeesByDepartment = function () {
    return function (item) {
        if (item.department == 'VS')
        {
            return true;
        }
        return false;
    };
};
Here the item is an employee inside my employees collection. If the employees’ department is “VS”, I should include it in the dropdown else I shouldn’t.

And this is my filtered employees.
image
Result with Filter
Even I can pass parameters to filterEmployeesByDepartment function.
<select ng-options="employee.name for employee in employees | filter:filterEmployeesByDepartment('Hello World')"
        ng-model="selectedEmployee">
</select>
And if I change the function accordingly,
$scope.filterEmployeesByDepartment = function (param) {
    return function (item) {
        console.log(param); // param->Hello World
    
        if (item.department == 'VS') {
            return true;
        }
        return false;
    };
};
Here, param will have the value “Hello World”.

Happy Coding.

Regards,
Jaliya

4 comments:

  1. Great, thanks :-)

    ReplyDelete
  2. Hi,

    Great work. Very good explanation.
    In the above code, instead of declaring a function, I hope we can also straight away specify the filter inline like
    ng-options="employee.name for employee in employees | filter:{department:'vs'}" ng-model="selectedEmployee"


    Thanks,
    Harini

    ReplyDelete
  3. Hi,

    This article was indeed very helpful to me.

    Thank you,
    Regards
    Amey

    ReplyDelete