A filter is a way to format the value of an expression to the required shape. By default AngularJS provides many filters like currency, date, json, limitTo, lowercase, number, orderBy & uppercase. You can also create your own Custom Filters. Let us talk about the below Example. Here I Created an angular custom filter to Reverse a String. Let me explain the program how it is working.
Example of Angular Custom Filter
First to add AngularJS library I added script tag with Google API file “angular.min.js”. By referring this with ng-app tag in my html page I made integrated AngularJS Framework to my App. Next I Created an AngularJS module named as “DemoApp”. To create a module in AngularJS I used angular.module Syntax. This is assigned to html body tag using ng-app from AngularJS. It says the body tag is in the scope of module.
In my page I have a simple input control. What I want is on adding text in this input box I want to display the input value in both the order original & reverse order. After created the module, I added a filter method from AngularJS. Which accepts 2 parameters. The first parameter is name of the Custom Filter & the Second one is the Function which return a Function with result of reverse input.
Using charAt, I am printing the index characters and concatenating result with this as a return result. In html body part finally I am calling our reverse custom filter for Filtered Value. The syntax is as below.
{{ text | reverse }}
– Copy this Code to Notepad.
– Save this as a html file. Open this in your Browser.
AngularJS Demo App to Reverse a String
<meta charset="UTF-8"> <title>Using Custom Filter to Reverse a String in AngularJS</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> <script type="text/javascript"></p> <p>var app = angular.module("DemoApp", []);</p> <p>app.filter("reverse", function() {<br /> return function(input) {<br /> var result = "";<br /> input = input || "";<br /> for (var i=0; i<input.length; i++) { result = input.charAt(i) + result; } return result; }; }); </script> <input type="text" ng-model="text" placeholder="Enter your inputs here..."> Input Value : {{ text }} Filtered Value : {{ text | reverse }}