Using Custom Filter to Reverse a String in AngularJS

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 issue. Here I want to Create a Custom Filter for Reverse a String. Let me explain in program below how it working.

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 }}

Example of Custom Filter

– Copy this Code to Notepad.
– Save this as a html file. Open this in your Browser.

AngularJS Demo App to Reverse a String

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Using Custom Filter to Reverse a String in AngularJS</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

<script type="text/javascript">

var app = angular.module("DemoApp", []);

app.filter("reverse", function() {
return function(input) {
var result = "";
input = input || "";
for (var i=0; i<input.length; i++) {
result = input.charAt(i) + result;
}
return result;
};
});

</script>

</head>
<body ng-app="DemoApp">
<input type="text" ng-model="text" placeholder="Enter your inputs here..."/>
<p>Input Value : {{ text }}</p>
<p>Filtered Value : {{ text | reverse }}</p>
</body>
</html>