Detailed explanation of using Filters in Angularjs_AngularJS
May 16, 2016 pm 03:11 PMThe function of Filter is to receive an input, process it through a certain rule, and then return the processed result to the user. Filter can be used in templates, controllers, or services, and it is also easy to customize a Filter.
Use Filter in template
Filter can be used in view templates using the following syntax expression:
{{ expression | filter }}
For example: The format {{ 12 | currency }} uses currency filter usage to filter the number 12 into currency form, and the result is $12.00.
Filter can be applied to the results of another filter. This is called "chaining" and is used with the following syntax:
{{ expression | filter1 | filter2 | ... }}
Parameters may be required in Filter. The syntax is:
{{ expression | filter:argument1:argument2:... }}
For example: The format {{ 1234 | number:2 }} uses the filter usage of number to filter the number 1234 into a number with two decimal points. The result is: 1,234.00.
Use filter
in controllers, services and directives
You can use filters in controllers, services, and directives.
To do this, you need to inject the dependency name into your controller/service/directive: filter; for example: if a filter is number, you need to inject numberFilter by using the dependency. The injected parameter is a function that takes a value as the first parameter and then uses the second parameter to filter the parameters.
The following example uses a Filter called filter. This filter can reduce arrays based on sub arrays. You can also apply markup in the view template, like: {{ctrl.array|filter:'a'}}, which will do a full-text search for 'a'. However, using filters in the view template will re-filter each filter, and if the array is relatively large, it will be loaded multiple times.
So the following example directly calls the filter in the controller. Through this, the controller can call the filter when needed (for example: when the backend data is loaded or the filter expression changes).
index.html:
<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.filteredArray">{{entry.name}} </span> </div> </div>
script.js:
angular.module('FilterInControllerModule', []). controller('FilterController', ['filterFilter', function(filterFilter) { this.array = [ {name: 'Tobias'}, {name: 'Jeff'}, {name: 'Brian'}, {name: 'Igor'}, {name: 'James'}, {name: 'Brad'} ]; this.filteredArray = filterFilter(this.array, 'a'); }]);
The result is:
All entries: Tobias Jeff Brian Igor James Brad Entries that contain an "a": Tobias Brian James Brad
Create custom filters:
Writing your own filter is very simple: just register a new filter factory function in your module. Internally, filterProvider is used here. This factory function should return a new filter function with the input value as the first argument. Any filter parameters are passed as additional parameters to the filter function.
This filter function should be a simple function. This means it should be stateless and idempotent. When the input function changes, Angular relies on these properties and executes the filter.
Note: The name of the filter must be a valid angular expression identifier. For example uppercase or orderBy. Special characters are not allowed in the name, such as hyphens and periods are not allowed. If you want your filter to be namespaced, then you can use uppercase (myappSubsectionFilterx) or underscore (myapp_subsection_filterx).
The following example filter reverses a string. In addition, it can add a condition to make the string uppercase.
index.html
<div ng-controller="MyController"> <input ng-model="greeting" type="text"><br> No filter: {{greeting}}<br> Reverse: {{greeting|reverse}}<br> Reverse + uppercase: {{greeting|reverse:true}}<br> Reverse, filtered in controller: {{filteredGreeting}}<br> </div>
script.js
angular.module('myReverseFilterApp', []) .filter('reverse', function() { return function(input, uppercase) { input = input || ''; var out = ""; for (var i = 0; i < input.length; i++) { out = input.charAt(i) + out; } // conditional based on optional argument if (uppercase) { out = out.toUpperCase(); } return out; }; }) .controller('MyController', ['$scope', 'reverseFilter', function($scope, reverseFilter) { $scope.greeting = 'hello'; $scope.filteredGreeting = reverseFilter($scope.greeting); }]);
The result is:
No filter: hello Reverse: olleh Reverse + uppercase: OLLEH Reverse, filtered in controller: olleh
Stateful filters
It is strongly recommended to write stateful filters as these cannot be optimized with Angular, which often leads to performance issues. Many stateful filters are converted to stateless filters simply by exposing the hidden state as a model and converting it into a filter parameter.
However, if you need to write a stateful filter, you must mark the filter as $stateful, which means that it will be executed one or more times during each $digest cycle.
index,html
<div ng-controller="MyController"> Input: <input ng-model="greeting" type="text"><br> Decoration: <input ng-model="decoration.symbol" type="text"><br> No filter: {{greeting}}<br> Decorated: {{greeting | decorate}}<br> </div>
script.js:
angular.module('myStatefulFilterApp', []) .filter('decorate', ['decoration', function(decoration) { function decorateFilter(input) { return decoration.symbol + input + decoration.symbol; } decorateFilter.$stateful = true; return decorateFilter; }]) .controller('MyController', ['$scope', 'decoration', function($scope, decoration) { $scope.greeting = 'hello'; $scope.decoration = decoration; }]) .value('decoration', {symbol: '*'});
The result is:
No filter: hello Decorated: *hello*
Next time I will write an article about the common usage of filter in angularjs.

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

VUE3 is currently a popular framework in front-end development. The basic functions it provides can greatly improve the efficiency of front-end development. Among them, filters are a very useful tool in VUE3. Using filters can easily filter, filter and process data. So what are filters? Simply put, filters are filters in VUE3. They can be used to process the rendered data in order to present more desirable results in the page. filters are some

Javascript is a very unique language. It is unique in terms of the organization of the code, the programming paradigm of the code, and the object-oriented theory. The issue of whether Javascript is an object-oriented language that has been debated for a long time has obviously been There is an answer. However, even though Javascript has been dominant for twenty years, if you want to understand popular frameworks such as jQuery, Angularjs, and even React, just watch the "Black Horse Cloud Classroom JavaScript Advanced Framework Design Video Tutorial".

In today's information age, websites have become an important tool for people to obtain information and communicate. A responsive website can adapt to various devices and provide users with a high-quality experience, which has become a hot spot in modern website development. This article will introduce how to use PHP and AngularJS to build a responsive website to provide a high-quality user experience. Introduction to PHP PHP is an open source server-side programming language ideal for web development. PHP has many advantages, such as easy to learn, cross-platform, rich tool library, development efficiency

Vue.js is a popular JavaScript framework that provides many useful features and tools to help front-end developers develop excellent applications. Among them, filters are a very useful function in Vue.js, which can be used for data formatting and filtering. In Vue, filters are equivalent to pipelines in templates and can be used to process and transform data. For example, we can use filters to change the date format from the original date to

With the continuous development of the Internet, Web applications have become an important part of enterprise information construction and a necessary means of modernization work. In order to make web applications easy to develop, maintain and expand, developers need to choose a technical framework and programming language that suits their development needs. PHP and AngularJS are two very popular web development technologies. They are server-side and client-side solutions respectively. Their combined use can greatly improve the development efficiency and user experience of web applications. Advantages of PHPPHP

With the rapid development of Web technology, Single Page Web Application (SinglePage Application, SPA) has become an increasingly popular Web application model. Compared with traditional multi-page web applications, the biggest advantage of SPA is that the user experience is smoother, and the computing pressure on the server is also greatly reduced. In this article, we will introduce how to build a simple SPA using Flask and AngularJS. Flask is a lightweight Py

With the popularity and development of the Internet, front-end development has become more and more important. As front-end developers, we need to understand and master various development tools and technologies. Among them, PHP and AngularJS are two very useful and popular tools. In this article, we will explain how to use these two tools for front-end development. 1. Introduction to PHP PHP is a popular open source server-side scripting language. It is suitable for web development and can run on web servers and various operating systems. The advantages of PHP are simplicity, speed and convenience

The content of this article is about the basic introduction to AngularJS. It has certain reference value. Now I share it with you. Friends in need can refer to it.
