How Do Angularjs Allows Us To Create Custom Filters
Posted By : Puneet Sharma | 30-May-2018
To create a custom filter, you must follow these steps:
- Pass a custom filter name and function as an input parameter for the app and create a filter using app.filter.
- Filter ()
- App.filter () will return a function
- Retuned function can take various optional input parameters
- The returned functions will have a custom filter code and will return the output.
Let's start with creating a very simple custom filter. We can apply this custom filter to a string and it will return to the capital case with each character.
MyApp.filter('toUpperCase', function () { return function (input) { var output = ""; output = input.toUpperCase(); return output; } })
We can use the toUpperCase custom filters in the view as shown below:
<html> <div ng-controller="ProductController"> <table class="table"> <tbody> <tr ng-repeat="a in products|filter:searchTerm"> <td>{{a.name|toUpperCase}}</td> <td>{{a.price}}</td> </tr> </tbody> </table> </div> </html>
We should keep in mind that the name of the custom filter is case sensitive, reading data from the
MyApp.controller("ProductController", function ($scope) { $scope.products = [ { 'name': 'pen', 'price': '200' }, { 'name': 'pencil', 'price': '400' }, { 'name': 'book', 'price': '2400' }, { 'name': 'ball', 'price': '400' }, { 'name': 'eraser', 'price': '1200' }, ]; })
Now we will get the product name given in the case of capital as shown in the image below:
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Puneet Sharma
Puneet is an experienced Lead UI Developer, having good knowledge of Angular Js, TypeScript, HTML5, CSS3, Javascript, Jquery, Photoshop.