Angularjs Examples

AJS Examples


AngularJS Custom Filter

Creating custome filter in AngularJS is quite easy. To create custome filter you need to register a new filter function with your module. Your function must return a new filter function which takes input value as the first argument. See below example.

Syntax

var app = angular.module('myApp', []);
   .filter('FilterName', function() {
    return function(input) {
      return variable;
    };
  })

AngularJS Custom Filter Example


<html>
<head>
<title>My first AngularJS Custom Filter Code</title>
<script SRC="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js">
</script>
<script>
var app = angular.module('myApp', []);

//Adding custom filter here
app.filter('CharCount', function() {
    return function(input) {
      input = input || '';
      var counter = 0;
      for (var i = 0; i < input.length; i++) {
        if(input.charAt(i) != ' ')
         counter = counter + 1;
      }
      
      return counter;
    };
  })

  //Adding controller here
   app.controller('CustomerController', function($scope) {
      $scope.Name = "Jimi Scott";
    });

</script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="CustomerController"> 
<input ng-model="Name" type="text"><br>
  Character Count: {{Name|CharCount}}<br>
</div>
</div>
</body>
</html>