Blog

  • 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 above created view controller as shown below:

    
    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:

    angular filter example result

Tags: AngularJS