AngularJS過濾器

  • code.angularjs.org/1.6.10/docs…
  • 內容
    • 在視圖模板使用過濾器
    • 何時執行過濾器
    • 在控制器、服務和指令中使用過濾器
    • 建立一個自定義過濾器
    • 有狀態的過濾器
    • 測試自定義過濾器

Filters format the value of an expression for display to the user. They can be used in view templates, controllers or services. AngularJS comes with a collection of built-in filters, but it is easy to define your own as well.angularjs

過濾器將表達式的值格式化以便顯示給用戶看。過濾器能夠用在視圖模板上,控制器上或服務器上。AngularJS附帶一系列內置的過濾器,可是也一樣能夠自定義你本身的過濾器。express

The underlying API is the $filterProvider.後端

底層API是$filterProvider。api

在視圖模板使用過濾器

Filters can be applied to expressions in view templates using the following syntax:數組

過濾器在視圖模板中使用如下語法表述bash

{{ expression | filter }}
複製代碼

E.g. the markup {{ 12 | currency }} formats the number 12 as a currency using the currency filter. The resulting value is $12.00.服務器

例子:使用過濾器將數字12格式化爲貨幣。結果是$12.00。 Filters can be applied to the result of another filter. This is called "chaining" and uses the following syntax: 過濾器能夠使用另外一個過濾器的結果,這種方式叫作「過濾器的疊加」,使用如下方法表述app

{{ expression | filter1 | filter2 | ... }}
複製代碼

Filters may have arguments. The syntax for this isless

過濾器一樣也能夠帶有參數。表達式以下:ide

{{ expression | filter:argument1:argument2:... }}
複製代碼

E.g. the markup {{ 1234 | number:2 }} formats the number 1234 with 2 decimal points using the number filter. The resulting value is 1,234.00.

例子:使用過濾器將數字1234格式化爲帶有兩位小數,結果是1234.00

何時執行過濾器

In templates, filters are only executed when their inputs have changed. This is more performant than executing a filter on each $digest as is the case with expressions.

在模板中,過濾器僅在輸入已更改時執行。這種方式更高效。

There are two exceptions to this rule:

此規則有兩個例外:

  1. In general, this applies only to filters that take primitive values as inputs. Filters that receive Objects as input are executed on each $digest, as it would be too costly to track if the inputs have changed.

一般,這僅適用於將原始值做爲輸入的過濾器。接收對象做爲輸入的過濾器將在每一個上執行$digest,由於若是輸入已更改,則跟蹤過於昂貴。

  1. Filters that are marked as stateful are also executed on eachdigest. See Stateful filters for more information. Note that no AngularJS core filters are $stateful.

標記爲stateful的過濾器也會在每一個digest上執行。有關詳細信息,請參閱狀態過濾器。注意AngularJS核心過濾器不是$stateful

在控制器、服務和指令中使用過濾器

You can also use filters in controllers, services, and directives.

For this, inject a dependency with the name Filter into your controller/service/directive. E.g. a filter called number is injected by using the dependency numberFilter. The injected argument is a function that takes the value to format as first argument, and filter parameters starting with the second argument.

爲此,請將具備名稱的依賴注入您的控制器、服務和指令中。例如:一個過濾器的名字叫作number,經過使用依賴項注入到調用的過濾器,注入的參數是一個函數,它將值格式化爲第一個參數,並從第二個參數開始過濾參數。

The example below uses the filter called filter. This filter reduces arrays into sub arrays based on conditions. The filter can be applied in the view template with markup like {{ctrl.array | filter:'a'}}, which would do a fulltext search for "a". However, using a filter in a view template will reevaluate the filter on every digest, which can be costly if the array is big.

下面的例子使用了一個名爲filter的過濾器。這個過濾器根據條件將數組縮減爲子數組。這個過濾器能夠在視圖模板中以以下方式顯示

{{ctrl.array | filter:'a'}}
複製代碼

就是在整個文檔裏查找"a",可是,在視圖模板中使用過濾器,若是數據很大,很浪費性能。 The example below therefore calls the filter directly in the controller. By this, the controller is able to call the filter only when needed (e.g. when the data is loaded from the backend or the filter expression is changed).

下面的例子是在控制器中使用過濾器,控制器只在須要時調用過濾器(例如:當從後端加載數據或更改過濾器表達式時)

<div ng-controller="FilterController as ctrl">
  <div>
    All entries:
    <span ng-repeat="entry in ctrl.array">{{entry.name}} </span>
  </div>
  <div>
    Entries that contain an "a":
    <span ng-repeat="entry in ctrl.filteredArray">{{entry.name}} </span>
  </div>
</div>

angular.module('FilterInControllerModule', []).
controller('FilterController', ['filterFilter', function FilterController(filterFilter) {
  this.array = [
    {name: 'Tobias'},
    {name: 'Jeff'},
    {name: 'Brian'},
    {name: 'Igor'},
    {name: 'James'},
    {name: 'Brad'}
  ];
  this.filteredArray = filterFilter(this.array, 'a');
}]);
複製代碼

建立一個自定義過濾器

Writing your own filter is very easy: just register a new filter factory function with your module. Internally, this uses the filterProvider. This factory function should return a new filter function which takes the input value as the first argument. Any filter arguments are passed in as additional arguments to the filter function.

建立自定義過濾器很容易,只需在模塊中註冊一個新的過濾器工廠功能。在內部,這使用了filterProvider。此工廠函數應返回一個新的過濾器函數,該函數將輸入值做爲第一個參數。任何過濾器參數都做爲過濾器函數的附加參數傳入。

The filter function should be a pure function, which means that it should always return the same result given the same input arguments and should not affect external state, for example, other AngularJS services. AngularJS relies on this contract and will by default execute a filter only when the inputs to the function change. Stateful filters are possible, but less performant.

filter函數應該是一個純函數,這意味着它應該老是在給定相同輸入參數的狀況下返回相同的結果,而且不該該影響外部狀態,例如,其餘AngularJS服務。AngularJS依賴於此合約,而且默認狀況下僅在函數輸入發生更改時才執行過濾器。 狀態過濾器是可能的,但性能較差。

Note: Filter names must be valid AngularJS Expressions identifiers, such as uppercase or orderBy. Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace your filters, then you can use capitalization (myappSubsectionFilterx) or underscores (myapp_subsection_filterx).

注意:過濾器名稱必須是有效的AngularJS Expressions標識符,例如uppercase或orderBy。不容許使用帶有特殊字符的名稱,例如連字符和點。若是您但願對過濾器命名空間,則能夠使用大寫(myappSubsectionFilterx)或下劃線(myapp_subsection_filterx)。

The following sample filter reverses a text string. In addition, it conditionally makes the text upper-case.

如下示例過濾器反轉文本字符串。另外,它有條件地使文本爲大寫。

<div ng-controller="MyController">
  <input ng-model="greeting" type="text"><br>
  No filter: {{greeting}}<br>
  Reverse: {{greeting|reverse}}<br>
  Reverse + uppercase: {{greeting|reverse:true}}<br>
  Reverse, filtered in controller: {{filteredGreeting}}<br>
</div>

angular.module('myReverseFilterApp', [])
.filter('reverse', function() {
  return function(input, uppercase) {
    input = input || '';
    var out = '';
    for (var i = 0; i < input.length; i++) {
      out = input.charAt(i) + out;
    }
    // conditional based on optional argument
    if (uppercase) {
      out = out.toUpperCase();
    }
    return out;
  };
})
.controller('MyController', ['$scope', 'reverseFilter', function($scope, reverseFilter) {
  $scope.greeting = 'hello';
  $scope.filteredGreeting = reverseFilter($scope.greeting);
}]);
複製代碼

有狀態的過濾器

It is strongly discouraged to write filters that are stateful, because the execution of those can't be optimized by AngularJS, which often leads to performance issues. Many stateful filters can be converted into stateless filters just by exposing the hidden state as a model and turning it into an argument for the filter.

強烈建議不要編寫有狀態的過濾器,由於AngularJS沒法優化這些過濾器的執行,這一般會致使性能問題。只需將隱藏狀態做爲模型公開並將其轉換爲過濾器的參數,就能夠將許多有狀態過濾器轉換爲無狀態過濾器。

If you however do need to write a stateful filter, you have to mark the filter as stateful, which means that it will be executed one or more times during the eachdigest cycle.

可是,若是您確實須要編寫有狀態過濾器,則必須將過濾器標記爲stateful,這意味着它將在每一個digest循環期間執行一次或屢次。

<div ng-controller="MyController">
  Input: <input ng-model="greeting" type="text"><br>
  Decoration: <input ng-model="decoration.symbol" type="text"><br>
  No filter: {{greeting}}<br>
  Decorated: {{greeting | decorate}}<br>
</div>

angular.module('myStatefulFilterApp', [])
.filter('decorate', ['decoration', function(decoration) {

  function decorateFilter(input) {
    return decoration.symbol + input + decoration.symbol;
  }
  decorateFilter.$stateful = true;

  return decorateFilter;
}])
.controller('MyController', ['$scope', 'decoration', function($scope, decoration) {
  $scope.greeting = 'hello';
  $scope.decoration = decoration;
}])
.value('decoration', {symbol: '*'});
複製代碼
相關文章
相關標籤/搜索