2016/05/24

Angular.js custom filters

下方的範例只有將文字轉換成大小寫以及偶數和奇數


<!DOCTYPE html>
<html ng-app="test">
 <head>
  <title>hi</title>
  <meta charset="utf-8">
  <script  src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
  <script type="text/javascript">
   var app = angular.module('test', []);
   app.controller('testController', function($scope){
    $scope.number = [1, 2, 3, 4, 5, 6, 7, 8];
   });

   app.filter('upperCase', function(){
    return function(str){
     return str.toUpperCase();
    }
   });

   app.filter('lowerCase', function(){
    return function(str){
     return str.toLowerCase();
    }
   });

   app.filter('evenNumber', function(){
    return function(number){
     var array = [];
     angular.forEach(number, function(v){
      if(v%2==0)
       array.push(v);
     })
     return array;
    }
   });

   app.filter('oldNumber', function(){
    return function(number){
     var array = [];
     angular.forEach(number, function(v){
      if(v%2!=0)
       array.push(v);
     })
     return array;
    }
   });

  </script>
 </head>
 <body ng-controller="testController">
  <p ng-bind="'hello,world' | upperCase"></p>
  <p ng-bind="'HELLO, WORLD' | lowerCase"></p>
  偶數
  <div ng-repeat="n in number | evenNumber">
   {{n}}
  </div>
  奇數
  <div ng-repeat="n in number | oldNumber">
   {{n}}
  </div>
 </body>
</html>


執行結果: