Explain custom filters with an example.

We can create our own filters in AngularJS. It can be performed by associating the filter to our module. These types of filters are known as custom filters.

An example given below can be used to count the number of elements in the string by using the filter:

angular.module(‘myCountFilterApp’, [])
.filter(‘count’,function()
{
return(function(input)
{
var out=[];
out=input.split(‘,’);
return out.length;
})
});
As per above example, if the string is “21, 34, 45” then output after applying filter will be 3.

AngularJS is an older JavaScript framework, and its use has been largely deprecated in favor of newer versions like Angular (2+). However, if you are specifically looking for information on custom filters in AngularJS, here’s an explanation along with an example.

In AngularJS, filters are used to format data before rendering it in the view. Custom filters allow you to define your own filtering logic to be applied to data in your AngularJS application.

Here’s an example of creating a custom filter in AngularJS:

html
<!DOCTYPE html>
<html lang=”en” ng-app=”customFilterApp”>
<head>
<meta charset=”UTF-8″>
<title>Custom Filter Example</title>
<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js”></script>
</head>
<body><div ng-controller=”CustomFilterController”>
<input type=”text” ng-model=”searchTerm” placeholder=”Enter search term”>

<ul>
<li ng-repeat=”item in items | customFilter:searchTerm”>{{ item.name }}</li>
</ul>
</div>

<script>
angular.module(‘customFilterApp’, [])
.filter(‘customFilter’, function () {
return function (items, searchTerm) {
var filtered = [];

// Custom filtering logic (e.g., filtering items based on the search term)
angular.forEach(items, function (item) {
if (item.name.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1) {
filtered.push(item);
}
});

return filtered;
};
})
.controller(‘CustomFilterController’, function ($scope) {
$scope.items = [
{ name: ‘Apple’ },
{ name: ‘Banana’ },
{ name: ‘Cherry’ },
{ name: ‘Date’ },
// … additional items
];
});
</script>

</body>
</html>

In this example:

  1. The customFilter filter is created using the .filter method of the AngularJS module. This filter takes an array of items and a search term as parameters and returns a filtered array based on the custom logic defined within the filter function.
  2. In the HTML, an input field is used to enter the search term, and the ng-repeat directive is used to iterate over the items array, applying the custom filter (customFilter) based on the entered search term.
  3. The custom filter function checks if the name property of each item contains the search term (case-insensitive). If it does, the item is included in the filtered result.

Note: Keep in mind that AngularJS is no longer actively maintained, and it’s recommended to use newer versions of Angular for modern web development