Tuesday 22 March 2016

Custom Filter in AngularJS

1. What is Filter in AngularJS.
AngularJs provide the in build filter which will modify your output. There are  certain inbuilt filters like.
LowerCase : which will change the output as lower case.
Upper Case : which will change the output as Upper case
Number : which will change it to number type.
Currency : Convert out put to currency type.

On the same line AngularJS give the facility to extend the filter and we can create our own custom filter.

2. What is Custom Filters.
Create your own filter to modify the output.
Lets see the two type of custom filter in AngularJs which is very simple to understand and Helpful to know of the custom filter will create.



To work with custom filter in AngularJS  we just need to extend the .filter method in AngularJs.

Code snippet :

there is two different type of custom filter defined in below code
1. capitalize : Make first charater is capital value
2. blankIfNegative : Empty value if the input value is negative



<!doctype html>
<html ng-app="myApp">
<head>
  <title>Simple App</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.js"></script>
</head>
<body>


  <div>
    <h5>Custom Capitalize Filter:</h5>
    <h2>{{ 'MY NAME is AngularJS' | lowercase | capitalize }}</h2>
  </div>

  <div>
    <h5>Custom make it blankIfNegative Filter:</h5>
    <h2>{{ 10 | blankIfNegative }}</h2>
    <h2>{{ -10 | blankIfNegative }}</h2>
  </div>

  <script>
    angular.module('myApp', ['myApp.filters']);

    angular.module('myApp.filters', [])
    .filter('capitalize', function() {
      return function(input) {
        // input will be the string we pass in
        if (input) {
          return input[0].toUpperCase() + input.slice(1);
        }
      }
    })
    .filter('blankIfNegative', function() {
      return function(input) {
        if (input <= 0) return ' ';
        else return input;
      }
    });
  </script>

</body>

</html>

Output :



1 comment:

  1. Thanks admin,I had spend more time with your website, because this is one of the best resources I have have found it.Your information is really useful to me.
    Regards,
    Angularjs Training | Angularjs Training in Chennai | Angularjs course in Chennai

    ReplyDelete