English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The filter (filter) as the name implies, its function is to receive an input, process it through a certain rule, and then return the processed result. It is mainly used for data formatting, such as getting a subset of an array, sorting elements in an array, etc. ng has built-in some filters, which are: currency (currency), date (date), filter (substring matching), json (formatting JSON object), limitTo (limit number), lowercase (lowercase), uppercase (uppercase), number (number), orderBy (sort). In total, there are nine. In addition, you can also customize filters, which is very powerful and can meet any data processing requirements.
The content of the filter is very simple, as long as you understand how to use the built-in filters and how to define your own filter, it's fine~ I have learned a lot about the system today, and here is an introduction.
Two ways to use filter
1. Using filter in the template
We can directly use filter in {{}}, followed by | to separate the expression, the syntax is as follows:
{{ expression | filter }}
Also, multiple filters can be used together, where the output of the previous filter is used as the input for the next filter (no wonder it looks like a pipeline...)
{{ expression | filter1 | filter2 | ... }}
Filters can accept parameters, which are separated by :, as follows:
{{ expression | filter:argument1:argument2:... }}
In addition to formatting data in {{}}, we can also use filters in directives, for example, first filter the array array and then output in a loop:
<span ng-repeat="a in array | filter ">
2. Using filter in controller and service
We can also use filters in our JavaScript code, the method is the familiar dependency injection. For example, if I want to use the currency filter in the controller, I just need to inject it into the controller, as follows:
app.controller('testC',function($scope,currencyFilter){ $scope.num = currencyFilter(123534); }
You can directly output $ in the template by using {{num}}.123,534The number is now formatted to two decimal places! The same principle applies when using filters in services.
You may be puzzled at this point, if I want to use multiple filters in the controller, do I have to inject them one by one, which is quite cumbersome? Don't worry, little brother~ Angular (ng) provides a $filter service that can be used to call the required filters. You only need to inject one $filter, and the usage is as follows:
app.controller('testC',function($scope,$filter){ $scope.num = $filter('currency')(123534); $scope.date = $filter('date')(new Date()); }
This can achieve the same effect. The advantage is that you can conveniently use different filters.
Built-in filters of Angular (ng)
Angular (ng) has built-in nine filters, and their usage is very simple, as you can understand from the documentation. However, in order to avoid looking up the documentation in the future, I still make a detailed record here.
1. currency (currency processing)
Using currency, you can format numbers into currency. The default is the dollar sign, and you can enter the symbol you need, for example, I entered the RMB:
{{num | currency : '¥'}}
2. date (date formatting)
The native JavaScript has limited ability to format dates, and the date filter provided by Angular (ng) can basically meet the general requirements for date formatting. Usage is as follows:
{{date | date : 'yyyy'}}-MM-dd hh:mm:ss EEEE'}}
The parameter is used to specify the desired format, y M d h m s E respectively represent year month day hour minute second week, you can freely combine them. You can also use different numbers to limit the number of digits formatted. In addition, the parameter can also use specific descriptive strings, such as 'shortTime' will format the time as12:05 such as pm. Angular provides eight descriptive strings, personally I think these are a bit redundant, I can completely combine the desired format according to my own wishes, and I don't want to remember so many words~
3.filter(matching substring)
This filter named filter (one must say that the name is easy to confuse——!)is used to process an array, and then it can filter out elements containing a certain substring, returning them as a sub-array. It can be a string array or an object array. If it is an object array, it can match the value of the attribute. It takes a parameter to define the matching rule of the substring. Let me give you an example to illustrate the usage of the parameter, I used several popular children to define an array:
$scope.childrenArray = [ {name:'kimi',age:3}, {name:'cindy',age:4}, {name:'anglar',age:4}, {name:'shitou',age:6}, 5} ] $scope.func = function(e){return e.age>4;}
{{ childrenArray | filter : 'a' }} //matching the attribute value containing a {{ childrenArray | filter : 4 }} //matching the attribute value containing4 {{ childrenArray | filter : {name : 'i'} }} //The parameter is an object, matching the name attribute containing i {{childrenArray | filter : func }} //The parameter is a function, specifying the return age>4
4.json(formatted JSON object)
The JSON filter can format a JavaScript object into a JSON string without any parameters. What is the use of this, I usually wouldn't output a JSON string on the page either, the official website says it can be used for debugging,嗯, it's a good choice. Or, it can also be used in JavaScript, its function is the same as the familiar JSON.stringify(). The usage is extremely simple:
{{ jsonTest | json}}
5. limitTo(limit array length or string length)
The limitTo filter is used to truncate arrays or strings, taking a parameter to specify the truncation length. If the parameter is negative, it starts truncating from the end of the array. Personally, I think this filter is a bit useless, first of all, it can only truncate from the beginning of the array or string,/截取尾部,secondly, the native JavaScript functions can replace it, let's see how to use it:
{{ childrenArray | limitTo : 2 }} //It will display the first two items in the array
6. lowercase(lowercase)
Convert the data to all lowercase. Too simple, no need to explain. It's also a very useless filter, without parameters, it can only convert the entire string to lowercase and cannot specify letters. I'm too lazy to write how to use it.
7. uppercase(uppercase)
Same as above.
8. number(formatted number)
The number filter can add a thousand separator to a number, like this,123,456,789. It also accepts a parameter that can specify how many decimal places to retain for the float type:
{{ num | number : 2 }}
9. orderBy(sorting)
The orderBy filter can sort the elements of an array, taking a parameter to specify the sorting rule. The parameter can be a string, indicating sorting by the attribute name. It can also be a function that defines the sorting attribute. It can also be an array, indicating sorting in sequence by the attribute values in the array (if the first compared value is equal, then compare the second item), let's take the above child array as an example:
<div>{{ childrenArray | orderBy : 'age' }}</div>/div> //Sort by the age attribute value, if-If the age is reversed <div>{{ childrenArray | orderBy : orderFunc }}</div>/div> //Sort by the return value of the function <div>{{ childrenArray | orderBy : ['age','name'] }}</div>/div> //If the age is the same, sort by name
The built-in filters have been introduced, and I'm almost asleep while writing them... As you can see, the built-in filters of ng are not omnipotent either; in fact, many of them are quite useless. For more personalized needs, we need to define our own filters. Let's take a look at how to customize filters.
Custom filter
Customizing filters is also very simple, use the filter method of the module, return a function that receives input values and returns the processed result. Without further ado, let's write one to see. For example, I need a filter that can return the elements with odd indices in an array, the code is as follows:
app.filter('odditems',function(){ return function(inputArray){ var array = []; for(var i=0;i<inputArray.length;i++{ if(i%2!==0){ array.push(inputArray[i]); } } return array; } });
The format is like this, your processing logic is written in the closure function inside. You can also make your filter accept parameters, which are defined in the return function as the second parameter, or more parameters can also be defined.
That's all there is to know about filters. As always, more learning needs to be tested by real projects. So, before the project comes, let's lay a solid foundation first~
That's all for this article. Hope it helps everyone's learning and that everyone will support the Yelling Tutorial more.
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, does not edit the content artificially, and does not assume relevant legal liabilities. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)