Home >Web Front-end >JS Tutorial >Detailed explanation of custom filters in AngularJS_AngularJS
Filter, as its name suggests, is to receive an input, process it according to a certain rule, and then return the processed result. It is mainly used for data formatting, such as obtaining a subset of an array, sorting elements in an array, etc. ng has some built-in filters, they are: currency (currency), date (date), filter (substring matching), json (formatted json object), limitTo (limit number), lowercase (lowercase), uppercase (uppercase) ), number (number), orderBy (sort). Nine types in total. In addition, you can also customize filters, which is powerful and can meet any data processing requirements.
AngularJS provides us with some built-in filters. Here are some scenarios for custom filters.
Custom filter without parameters
//过滤 不带参数 app.filter('ordinal', function () { return function (number) { if (isNaN(number) || number < 1) { return number; } else { var lastDigit = number % 10; if (lastDigit === 1) { return number + 'st' } else if (lastDigit === 2) { return number + 'nd' } else if (lastDigit === 3) { return number + 'rd' } else if (lastDigit > 3) { return number + 'th' } } } });
Used roughly like this:
{{777 | ordinal}}
Filtering with parameters
Convert letters in a certain position to uppercase.
//过滤 带参数 app.filter('capitalize', function () { //input 需要过滤的元素 //char位置,索引减一 return function (input, char) { if (isNaN(input)) { //如果序号位置没有设置,索引位置默认是0 var char = char - 1 || 0; //把过滤元素索引位置上的字母转换成大写 var letter = input.charAt(char).toUpperCase(); var out = []; for (var i = 0; i < input.length; i++) { if (i == char) { out.push(letter); } else { out.push(input[i]); } } return out.join(''); } else { return input; } } });
Used roughly like this:
{{'seven' | capitalize:3}}
Filter collection
Filter out the elements in the collection that meet certain conditions.
var app = angular.module('filters', []); app.controller('demo', function ($scope) { $scope.languages = [ {name: 'C#', type: 'static'}, {name: 'PHP', type: 'dynamic'}, {name: 'Go', type: 'static'}, {name: 'JavaScript', type: 'dynamic'}, {name: 'Rust', type: 'static'} ]; }); //过滤集合 app.filter('staticLanguage', function () { return function (input) { var out = []; angular.forEach(input, function (language) { if (language.type === 'static') { out.push(language); } }); return out; } });
Used roughly like this:
<li ng-repeat="lang in languages | staticLanguage">{{lang.name}}</li>
Filter, take multiple parameters, do multiple things
Define the display unit and display position of the number.
var app = angular.module('filters', []); app.controller('demo', function ($scope) { $scope.digit = 29.88; }); //过滤 做多件事 多个参赛 app.filter('customCurrency', function () { return function (input, symbol, place) { if (isNaN(input)) { return input; } else { //检查symbol是否有实参 var symbol = symbol || '¥'; var place = place === undefined ? true : place; if(place===true){ return symbol+input; }else{ return input + symbol; } } } });
Used roughly like this:
<p><strong>Original:</strong></p> <ul><li>{{digit}}</li></ul> <p><strong>Custom Currency Filter</strong></p> <ul> <li>{{digit | customCurrency}} --Default</li> <li>{{digit | customCurrency:'元'}} --custom symbol</li> <li>{{digit | customCurrency:'元':false}} -- custom symbol and custom location</li> </ul>
Two ways to use filter
1. Use filter
in the templateWe can use filter directly in {{}}, followed by | to separate the expression. The syntax is as follows:
{{ expression | filter }}
You can also use multiple filters together. The output of the previous filter will be used as the input of the next filter (no wonder this product looks like a pipe...)
{{ expression | filter1 | filter2 | ... }}
filter can receive parameters, and the parameters are divided by :, as follows:
{{ expression | filter:argument1:argument2:... }}
In addition to formatting the data in {{}}, we can also use filter in the instruction, for example, first filter the array and then loop the output:
<span ng-repeat="a in array | filter ">
2. Use filter in controller and service
Filters can also be used in our js code through the familiar dependency injection. For example, if I want to use the currency filter in a controller, I just need to inject it into the controller. The code is as follows:
app.controller('testC',function($scope,currencyFilter){ $scope.num = currencyFilter(123534); }
Use {{num}} in the template to directly output $123,534.00! The same goes for using filters in services.
At this point you may have doubts. If I want to use multiple filters in the controller, do I have to inject them one by one? Wouldn’t this be too laborious? Little brother, don’t worry~ng provides a $filter service to call the required filter. You only need to inject a $filter. The usage method is as follows:
app.controller('testC',function($scope,$filter){ $scope.num = $filter('currency')(123534); $scope.date = $filter('date')(new Date()); }
The same effect can be achieved. The advantage is that you can use different filters conveniently.