Pages

Saturday, September 24, 2016

Angular Js- Use a filter in expression with javascript addition operator

Recently in one of my Projects I was stuck up in an issue regarding filters

Here is My Custom Filter

       app.filter('alterCap',function()   
       {  
         return function(x)   
         {  
           var i, c, txt = "";  
           for (i = 0; i < x.length; i++) {  
             c = x[i];  
             if (i % 2 == 0) {  
               c = c.toUpperCase();  
             }  
             txt += c;  
           }  
           return txt;  
         };  
       });  

I am trying to use this filter in my HTML as

 {{ x.country|alterCap + ":" + x.capital|alterCap }}  

But this didn't worked out so I had to use filter in my controller.Here is how I did the same

 app.controller("myCtrl",function($scope,$filter){  
         $scope.capitals = [  
         {country:'India',capital:'Delhi'},  
         {country:'Sri Lanka',capital:'Colombo'},  
         {country:'Afganistan',capital:'Kabul'},  
         {country:'Bhutan',capital:'Norway'},  
         {country:'Nepal',capital:'Thimphu'},  
         {country:'Japan',capital:'Tokyo'},  
         {country:'China',capital:'Beijing'},  
         {country:'Russia',capital:'Moscow'},  
         {country:'USA',capital:'Washington, D.C.'}  
         ];  
         $scope.applyAlterCap = function(movie){  
           return $filter('alterCap')(movie);  
         };  
       });  

And then I used this in my Html as follows

 <p>Using Custom Filter with addition operator inside expression</p>  
     <ul>  
       <li ng-repeat="x in capitals | orderBy:'capital'">  
         {{ applyAlterCap(x.country) + ":" + x.capital }}  
       </li>  
     </ul>  

No comments:

Post a Comment