【AnjularJS系列6】過濾器

第六篇,過濾器javascript

 

AngularJS 過濾器可用於轉換數據:java

過濾器 描述
currency 格式化數字爲貨幣格式。
filter 從數組項中選擇一個子集。
lowercase 格式化字符串爲小寫。
orderBy 根據某個表達式排列數組。
uppercase 格式化字符串爲大寫。

 

 

 

 

 

 

 

 

1、在模板中使用filter:直接在{{}}中使用filter,在表達式後用|進行分割express

    A、單一filter數組

      語法:{{ expression | filter }}app

      示例:<div ng-app="">ide

<span>lowercase:{{ "JUST Do It"| lowercase }}</span><br />
<span>uppercase:{{ "lower cap string" | uppercase }}</span><br />
<span>currency:{{ "250" | currency }}</span>
</div>
函數

      顯示結果:lowercase:just do it
                       uppercase:LOWER CAP STRING
                       currency:$250.00
spa

   B、能夠多個filter連用,上一個filter的輸出將做爲下一個filter的輸入3d

      語法:{{ expression | filter1 | filter2 | ... }}code

      示例:<div ng-app="">

<span>多個過濾器:</span><br />
<span>小數點,貨幣單位{{ "320"| number:2|currency }}</span><br />
</div>

      顯示結果:小數點,貨幣單位$320.00

      number先將數字保留兩位小數,currency再轉換成貨幣單位,其中,number:2就是如下要說明的帶參數的過濾器

   C、帶參數的過濾器

     1) currency :使用currency能夠將數字格式化爲貨幣,默認是美圓符號,你能夠本身傳入所需的符號

                           {{ "123"|currency:'¥' }}

      2) number : 能夠爲一個數字加上千位分割,例如,123,456,789。

                          同時接收一個參數,能夠指定小float類型保留幾位小數:

                          {{ num | number : 2 }}

      3) limitTo:limitTo過濾器用來截取數組或字符串,接收一個參數用來指定截取的長度。

                        {{ childrenArray|limitTo:2 }}(childrenArray爲已初始化的數組,下文亦是)

      4) orderBy :orderBy過濾器能夠將一個數組中的元素進行排序,

         參數能夠是一個字符串,表示以該屬性名稱進行排序。能夠是一個函數,定義排序屬性。

        還能夠是一個數組,表示依次按數組中的屬性值進行排序(若按第一項比較的值相等,再按第二項比較)

                {{ childrenArray|orderBy:'age'}}                   OR           {{ childrenArray|orderBy:['age','name']}}

   D、自定義過濾器:利用filter方法建立過濾器,將表達式做爲輸入,進行數據處理

         1)單一參數

            <span>{{childrenArray[0] |getChildName}}</span>

 1 <script type="text/javascript">   
 2     var app = angular.module('MyFilter', []);
 3     app.controller('MyFilterCtrl',function($scope) {
 4         $scope.childrenArray = [
 5         {name:'Kimi',age:3},
 6         {name:'Shitou',age:6},
 7         {name:'Anglar',age:4},
 8         {name:'Tiantian',age:5},
 9         {name:'Cindy',age:4}
10         ];
11     });
12     app.filter('getChildName',function(){
13         return function(inputArray){
14             return inputArray.name+"今年"+inputArray.age+"";
15         }
16     });
17 </script>
自定義過濾器

       2)多個參數

 

二、在controller和service中使用filter

相關文章
相關標籤/搜索