Home > Web Front-end > JS Tutorial > body text

Detailed explanation of custom filters in AngularJS_AngularJS

WBOY
Release: 2016-05-16 15:23:20
Original
1331 people have browsed it

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'
}
}
}
});
Copy after login

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;
}
}
}); 
Copy after login

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;
}
}); 
Copy after login

Used roughly like this:

<li ng-repeat="lang in languages | staticLanguage">{{lang.name}}</li>
Copy after login

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 &#63; true : place;
if(place===true){
return symbol+input;
}else{
return input + symbol;
}
}
}
}); 
Copy after login

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>
Copy after login

Two ways to use filter

1. Use filter

in the template

We can use filter directly in {{}}, followed by | to separate the expression. The syntax is as follows:

{{ expression | filter }}
Copy after login

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 | ... }}
Copy after login

filter can receive parameters, and the parameters are divided by :, as follows:

{{ expression | filter:argument1:argument2:... }}
Copy after login

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 ">
Copy after login

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); 
}
Copy after login

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()); 
}
Copy after login

The same effect can be achieved. The advantage is that you can use different filters conveniently.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!