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: '*'});
复制代码
相关文章
相关标签/搜索