AngularJS:Custom filter

AngularJS provides filters which are used to filter or/and format the data displayed to the user. Commonly filters are used for data-binding expressions but they can also be used within controllers, services and directives. Here is example of custom filter.

by Korah Babu Varghese

HTML

<div class="container">
  <div class="row">
    <div class="col-lg-6 col-lg-offset-3">
      <div ng-app="filters">
        <div ng-controller="demo">
          <div class="panel panel-default">
             <div class="panel-body">
               <h4 class="text-center">AngularJS Filter - Custom Currency</h4>
               <p><strong>Original:</strong></p>
               <ul class="list">
                 <li>{{example1}}</li>
               </ul>
               <p><strong>Custom Currency Filter:</strong></p>
               <ul class="list">
                 <li>{{example1 | customCurrency}} - Default</li>
                 <li>{{example1 | customCurrency:'€'}} - Custom Symbol</li>
                 <li>{{example1 | customCurrency:'€':false}} - Custom Symbol and Custom Location</li>
               </ul>
            </div>
          </div>
      </div>
    </div>
  </div>

 
</div>

CSS

body {
  
}

.credits {
  margin: 15px 0px;
}

.panel {
  margin: 15px 0px;
}

JavaScript

var app = angular.module('filters', []);

app.controller('demo', function($scope){
  $scope.example1 = 8760;
})

// To declare a filter we pass in two parameters to app.filter

// The first parameter is the name of the filter 
// second is a function that will return another function that does the actual work of the filter
app.filter('customCurrency', function(){
// In the return function, we must pass in a single parameter which will be the data we will work on.
  // We have the ability to support multiple other parameters that can be passed into the filter optionally
  return function(input){
    var num = input;
var hours = (num / 60);
var rhours = Math.floor(hours);
var minutes = (hours - rhours) * 60;
var rminutes = Math.round(minutes);
return num + " minutes = " + rhours + " hour(s) and " + rminutes + " minute(s).";
  }
})