AngularJS's filter (filter) is used to filter the value of a variable, or format the output, to get the desired result or format.
Filters can be added to expressions and directives using a pipe character (|).
For example: <p>Name is {{ lastName | uppercase }}</p> //Format the string to uppercase
1. Use filters in templates
Apply Filters in Expressions
The format needs to be followed as follows:
{{ expression | filter }} i.e. {{ expression | filter }}
For example: {{ 12 | currency }} outputs $12.00
{{expression | filter}}
{{12 | currency}} outputs $12.00
Apply Filters to output results
In layman's terms, it is the superposition of Filter - the output of the previous filter is used as the input data source of the next filter.
The format needs to be followed as follows:
{{ expression | filter1 | filter2 | ... }} That is, the expression (expression) is filtered by filter1 and then filtered by filter2...
{{expression | filter1 | filter2 | ..... }}
Filter with parameters
Filter can be followed by one or more parameters to help implement filters with special requirements and requirements.
The format needs to be followed as follows:
{{ expression | filter:argument1:argument2:... }}
Example: {{ 1234 | number: 2 }} = 1,234.00
{{expression | filter:argument1:argument2:...}}
2. AngularJS built-in filter
AngularJS provides us with 9 built-in filters
分别是currency, date, filter, json, limitTo, uppercase, lowercase, number, orderBy。
The specific usage is detailed in the AngularJS documentation. Below are just a few commonly used ones.
currency filter
currency – used to convert the variable to a currency representation
如:{{ amount | currency}}
<div>{{amount | currency}}<div>
uppercase/lowercase filter (letter case filter)
{{ "lower cap string" | uppercase }} <input ng-model="userInput"> Uppercased: {{ userInput | uppercase }}
date filter(date filter)
{{ 1304375948024 | date }} {{ 1304375948024 | date:"MM/dd/yyyy @ h:mma" }}
json filter
{{ {foo: "bar", baz: 23} | json }}
3. Custom filter
The way of writing custom filters in AngularJS is very similar to the factory service of AngularJS. You must remember that it returns an object or a function. When writing, you only need a function with more than one parameter.
The format is roughly as follows:
app.filter('filter (filter) name', function(){ return function (object to be filtered, filter parameter 1, filter parameter 2,...){ //...Execute business logic code return the processed object; } });
4. Use filter in controllers, services and drictives
可以在AngularJS的controller, service或者driective中使用filter, 这时候你需要将依赖的filter名字加入到controller, service或者directive的依赖中去。
在controller中直接使用filter, 这样controller可以根据自身需要而适时调用filter
<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.filterdArray">{{entry.name}}</span> </div> </div>