Home Web Front-end JS Tutorial Detailed explanation of custom filters in AngularJS_AngularJS

Detailed explanation of custom filters in AngularJS_AngularJS

May 16, 2016 pm 03:23 PM

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.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles