In AngularJS, filters are used to format data. AngularJS comes with a collection of built-in filters, but you can create your own filter.
I will show you in this tutorial how to create your own AngularJS filter. We will create a filter to capitalize a string.
Create simple filter
New filters are created using the module.filter() function. The implementation of the capitalize
filter will capitalize
the first character of the string.
<div ng-app="myApp" ng-init="names=['john', 'anne', 'peter', 'kevin', 'joe']"> <ol> <li ng-repeat="x in names">{{ x | capitalize }}</li> </ol> </div> <script> var app = angular.module('myApp', []); app.filter('capitalize', function() { return function(str) { firstChar = str.charAt(0).toUpperCase(); result = firstChar + str.substring(1); return result; }; }); </script>
Output
1. John 2. Anne 3. Peter 4. Kevin 5. Joe
Pass argument to filter
Instead of capitalizing the first character of the string, let's allow the users decide which character to turn into upper case.
For this new requirement, let's modify the code above to include the position
argument.
<div ng-app="myApp" ng-init="names=['john', 'anne', 'peter', 'kevin', 'joe']"> <ol> <li ng-repeat="x in names">{{ x | capitalize:2 }}</li> </ol> </div> <script> var app = angular.module('myApp', []); app.filter('capitalize', function() { return function(str, position) { upChar = str.charAt(position).toUpperCase(); result = str.substring(0,position) + upChar + str.substring(position+1); return result; }; }); </script>
Output
The filter was invoked with the position argument equal to 2. Therefore, the 3rd character of the string is capitalized.
1. joHn 2. anNe 3. peTer 4. keVin 5. joE