Friday, July 25, 2014

AngularJs Tutorials: built-in filters by example

AngularJs have a number of useful filters.
  • filter
  • currency
  • number
  • date
  • json
  • lowercase
  • uppercase
  • limitTo
  • orderBy
There is also a way to create a custom filter; here we will just discuss the built-ins:

Filter

The filter filter is very useful if you would like to remove a few items in an array. It is common to use this with ng-repeat

example;
 <html>  
 <head>  
 <script src="angular.min.js"></script>  
 </head>  
 <body ng-app>  
 <div ng-init="months= [ 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'july', 'aug', 'sept', 'oct', 'nov', 'dec' ]"></div>  
 include only words with 'ju': {{ months| filter:'ju' }}  
 <br/>  
 <br/>include only words without 'ju': {{ months| filter:'!ju' }}  
 <br/><br/>displaying months without 'ju'  
 <ul>  
      <li ng-repeat="mon in months| filter:'!ju' ">{{mon}}</li>  
 </ul>  
 </body>  
 </html>  

the example above will print:
angularjs built-in filter filter example
Sometimes you may want to display an item if it is contained in the array; you can do this by;
   <body ng-app>   
  <div ng-init="months = [ 'dog', 'cat', 'horse' ]"></div>   
  <ul>   
    <li ng-repeat="mon in months | filter:'dog':true ">{{mon}}</li>   
  </ul>   
  </body>   
Filter's 2nd parameter above, which is 'true', instructs filter to compare and give the exact value if it is in the array; (the above example is case sensitive). The expected output will print only 'dog'.

Filters are used in this form:
 { expression | the_filter : parameter1 : parameter2... }  

Our first filter, the "filter" (the name is getting funnier hehe)... the "filter" can accept 2 parameters.
The first parameter is an expression that tells filter of a "substring" match. Filter will filter words that contains the substring; and if "!" is prefixed then it does the opposite.

The first parameter can also be a function of the form "function(value){}". Just return true if you want to include the passed value. As an example below will try to display all odd numbers from 1 to 10:
 <html>  
 <head>  
 <script src="angular.min.js"></script>  
 <script type="text/javascript">  
 var app = angular.module("MyApp", []);  
 app.controller("FilterController", ["$scope", function($scope){  
      $scope.oddFilter = function(value) {  
           return (1 == (value & 0x1))  
      };  
 }]);  
 </script>  
 </head>  
 <body ng-app="MyApp">  
 <div ng-controller="FilterController">  
      <div ng-init="numbers = [ 1,2,3,4,5,6,7,8,9,10 ]"></div>  
      display only odd  
      <ul>  
           <li ng-repeat="num in numbers | filter:oddFilter ">{{num}}</li>  
      </ul>  
 </div>  
 </body>  
 </html>  

sample output:
angularjs built-in filter filter example

If your first parameter is an expression and you want to further filter the result you can do this using the 2nd parameter, which is a function of the form "function(actual,expected){}". Earlier we demonstrated the 2nd parameter with a bool value to exactly filter the word 'dog'.
  <html>   
  <head>   
  <script src="angular.min.js"></script>   
  <script type="text/javascript">   
  var app = angular.module("MyApp", []);   
  app.controller("FilterController", ["$scope", function($scope){   
       $scope.cmpSample = function(actual, expected) {  
           return (0<=actual.indexOf(expected)) && (0<=actual.indexOf('food'));  
       };  
  }]);   
  </script>    
  </head>   
  <body ng-app="MyApp">  
  <div ng-controller="FilterController">   
       <div ng-init="months = [ 'dog house', 'dog food', 'cat house', 'cat food' ]"></div>   
       <ul>   
            <li ng-repeat="mon in months | filter:'dog':cmpSample ">{{mon}}</li>   
       </ul>   
  </div>  
  </body>   
  </html> 

The above will use the "cmpSample()" function to filter the output base on the first parameter.  If you have "dog" as the first parameter like shown above; then the expected output is "dog food".  If your first parameter is "cat", then the expected output is "cat food".  This is because "cmpSample()" will also check if the value contains the word 'food'.

objects as input:

When you have objects as input in your filter, you can do:
  <html>   
  <head>   
  <script src="angular.min.js"></script>   
  <script type="text/javascript">   
  var app = angular.module("MyApp", []);   
  app.controller("FilterController", ["$scope", function($scope){   
    $scope.oddFilter = function(value) {   
       return (1 == (value & 0x1))   
    };  
       $scope.cmpSample = function(actual, expected) {  
           alert("what");  
           console.log(actual);  
           console.log(expected);  
       };  
  }]);   
  </script>   
  </head>   
  <body ng-app>   
    <div ng-init="animals = [ {pet:'dog k9', domesticated:true},  
                              {pet:'wolf k9', domesticated:false},  
                              {pet:'lion', domesticated:false},  
                              {pet:'cat', domesticated:true},  
                            ]"></div>   
    display only domesticated   
    <ul>   
       <li ng-repeat=" anim in animals | filter:{ domesticated: true } ">{{anim.pet}}</li>   
    </ul>   
       display only k9   
    <ul>   
       <li ng-repeat=" anim in animals | filter:{ pet: 'k9' } ">{{anim.pet}}</li>   
    </ul>   
  </body>   
  </html>   

sample output:

Currency

The currency filter allows you display a currency.
  <body ng-app>   
   {{1234|currency:'&#8369;'}}  
  </body>  

the example above displays:
angularjs built-in currency filter example

The currency filter will only accept one parameter, the currency symbol. The above example is a currency symbol for peso.

I am not sure if this works perfectly with other currencies though, but below is a list of other currencies.
 ₠     8352     EURO-CURRENCY SIGN  
 ₡     8353     COLON SIGN  
 ₢     8354     CRUZEIRO SIGN  
 ₣     8355     FRENCH FRANC SIGN  
 ₤     8356     LIRA SIGN  
 ₥     8357     MILL SIGN  
 ₦     8358     NAIRA SIGN  
 ₧     8359     PESETA SIGN  
 ₨     8360     RUPEE SIGN  
 ₩     8361     WON SIGN  
 ₪     8362     NEW SHEQEL SIGN  
 ₫     8363     DONG SIGN  
 €     8364     EURO SIGN  
 ₭     8365     KIP SIGN  
 ₮     8366     TUGRIK SIGN  
 ₯     8367     DRACHMA SIGN  
 ₰     8368     GERMAN PENNY SYMBOL  
 ₱     8369     PESO SIGN  
 ₲     8370     GUARANI SIGN  
 ₳     8371     AUSTRAL SIGN  
 ₴     8372     HRYVNIA SIGN  
 ₵     8373     CEDI SIGN  
 ₶     8374     LIVRE TOURNOIS SIGN  
 ₷     8375     SPESMILO SIGN  
 ₸     8376     TENGE SIGN  
 ₹     8377     INDIAN RUPEE SIGN  


Number

The number filter will format the expression to a number with the specified number of decimal places.
  <body ng-app>   
            1. {{ 1234567|number:0 }}  
      <br/>2. {{ 1234567|number:2 }}  
      <br/>3. {{ 1234567|number:4 }}  
      <br/>4. {{ "1234567"|number:4 }}  
      <br/>5. {{ "12345.67"|number:4 }}  
      <br/>6. {{ "ABCDE"|number:4 }}  
  </body>   

sample output:
angularjs built-in number filter example

Date

Good examples already provided by docs:
https://docs.angularjs.org/api/ng/filter/date

Json

Json will covert a javascript object to string.
 <body ng-app>  
 <div ng-init="UserModel = {name:'', address:''}">  
      <form>  
           name: <input type="text" ng-model="UserModel.name" /><br/>  
           addr: <input type="text" ng-model="UserModel.address" /><br/>  
      </form>  
      <br/>UserModel in json format:<br/>  
      {{ UserModel | json }}  
 </div>  
 </body>   

sample output:
angularjs built-in json filter example

Uppercase And Lowercase

 <body ng-app>  
      {{ "my string" | uppercase }}  
      <br/>{{ "MY STRING" | lowercase }}  
</body> 


LimitTo

If applied to string or array, will return only a length specified by limitTo.
 <body ng-app>  
      1. {{ [1,2,3,4,5,6,7,8,9,10] | limitTo:3 }} <br/>  
      2. {{ [1,2,3,4,5,6,7,8,9,10] | limitTo:-3 }} <br/>  
      3. {{ "hello foo bar!" | limitTo:4 }} <br/>  
      4. {{ "hello foo bar!" | limitTo:-4 }} <br/>  
 </body>    

sample output:
angularjs built-in limitTo filter example

OrderBy

Sorts the array input,
  <body ng-app>   
    <div ng-init="products = [ {product:'apple cider',  stocks:23},  
                 {product:'apple favorite', stocks:3},  
                 {product:'shoe box',    stocks:6},  
                 {product:'banana shake',  stocks:12},  
                 {product:'keyboard mouse', stocks:34},  
               ]"></div>   
    sorted by product   
    <ul>   
       <li ng-repeat=" prod in products | orderBy:'product' ">{{prod.product}}, {{prod.stocks}}</li>   
    </ul>   
    sorted by product, in reverse order  
    <ul>   
       <li ng-repeat=" prod in products | orderBy:'-product' ">{{prod.product}}, {{prod.stocks}}</li>   
    </ul>   
    sorted by stocks   
    <ul>   
       <li ng-repeat=" prod in products | orderBy:'stocks' ">{{prod.product}}, {{prod.stocks}}</li>    
    </ul>   
    sorted by stocks, in reverse  
    <ul>   
       <li ng-repeat=" prod in products | orderBy:'stocks' ">{{prod.product}}, {{prod.stocks}}</li>    
    </ul>   
  </body>   

sample output: