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",
}
];
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;
};
};
And this is my filtered employees.
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
Thank you!
ReplyDeleteGreat, thanks :-)
ReplyDeleteHi,
ReplyDeleteGreat 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
Hi,
ReplyDeleteThis article was indeed very helpful to me.
Thank you,
Regards
Amey
I am using the inline method described above. I am having an issue with a blank entry in the dropdown that is selected. Once I click a valid entry, the blank entry goes away. How can I get rid of the blank entry before the user gets access to the field?
ReplyDeleteThank you!! This really helped!!
ReplyDeleteThank you!! This is very helpfull!!
ReplyDelete