AngularJS custom filter example

In previous post, we have seen about angularJS inbuilt filter. In this post, we are going to how to create your own filters.

AngularJS tutorial:

    AngularJs hello world example AngularJs controller examples AngularJs ng-repeat example AngularJs Built-in filter example AngularJs custom filter example AngularJs ajax example using $http AngularJS RESTful web service JAXRS CRUD example using $http
Filters are used to format data in desired way.
For creating a filter , you need to attach it with the module.
angular.module('myApp')
  .filter('customFilter', function () {
    return function (input) {
      if (input) {
        return input;
      }
    };
  });
Lets take example where we will convert string to upper case and replace "_" by space(" ").

Example:

Copy below text , open notepad , paste it and save it as angularJSCustomFilterExample.html and open it in the browser.
<!DOCTYPE html>  
<html>  
<head>  
<meta charset="UTF-8">  
<title>Angular js</title>  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>  
 <script>
   var app = angular.module('myApp', []);
app.controller('java2blogContoller', function($scope) {
    $scope.java2blogMsg = "Hello_from_Java2blog";   
}).filter('java2blogFilter',function(){
 return function( str ) {
      return str.toUpperCase().replace(/_/g,' ');
   }
});
  </script>
</head>  
<body>  
<div ng-app="myApp" ng-controller="java2blogContoller">    
 </br>  
  {{java2blogMsg|java2blogFilter}}   !!!  
</div>  
</body>  
</html> 

Output:

HELLO FROM JAVA2BLOG !!!

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012