AngularJS Tutorial - Create a Custom Filter to Reverse an Input








The following code shows how to create a Custom Filter to Reverse an Input.

Example


<!doctype html>
<html  ng-app="MyApp">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
    <script>
var app = angular.module("MyApp", []);
<!-- ww w. j  a  v  a  2 s  .c om-->
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>
    <input type="text" ng-model="text" placeholder="Enter text"/>
    <p>Input: {{ text }}</p>
    <p>Filtered input: {{ text | reverse }}</p>
  </body>
</html>

The code above is rendered as follows: