Total Pageviews

2014/05/22

Create custom display filter in AngularJS

Requirement
Assume we have a drop down list which used to control the currency unit display.
It has two options, the first one is dollar. You can see the amount had been used dollar as its currency unit display.

The second option is a hundred million. You can see the amount had been used hundred million as its currency unit display.

Custom display filter
AngularJS provide some build-in filter, ex. number filter can used to determine If the input is not a number an empty string is returned.
In order to create a new filter, you are going to create a fms421rCurrency module and register your custom filter with this module:
   //根據資料單位下拉單的選項,決定顯示於前端的金額單位是元或億  
   app.filter('fms421rCurrency', ['$filter', function ($filter, $scope) {  
     var fun = function(input, id) {  
       try{  
         input = BigDecimalROUND_HALF_UP(input, id);  
         return input;  
       }catch (e) {  
         return "";  
       }  
     };  
    return fun;  
   }]);  
  //根據資料單位下拉單的選項,決定金額是否要除以100000000  
   var BigDecimalROUND_HALF_UP = function(input, id){  
     if(input == 0){  
       return new BigDecimal("0");  
     }  
     var numb = new BigDecimal(input.toString());  
     var bil = new BigDecimal("100000000");   
     if ("02"==id) {//01:元, 02:億  
       numb = numb.divide(bil,0, BigDecimal.prototype.ROUND_HALF_UP);  
     }  
     return numb;  
   };  

The syntax for using filters in Angular templates is as follows:
{{ expression | filter }}
We can apply the filter in the fms421r tempate page:
 <td class="text-right border-right">   
 {{fms421rDto.dayRslt1|fms421rCurrency:model.dataunit.id|fms421rnative|number}}  
 </td>   


Reference




No comments: