Use Filters in Angularjs for details, angularjsfilters

Source: Internet
Author: User

Use Filters in Angularjs for details, angularjsfilters

The Filter function is to receive an input, process it through a rule, and then return the processed result to the user. Filters can be used in templates, controllers, or services, and a Filter can be easily customized.

Use Filter in the template

Filter can be used to use the following syntax expression in the view template:

{Expression | filter }}

For example, the format {12 | currency} is used by currency filter. The result of filtering the number 12 as a currency is $12.00.

Filter can be applied to another Filter result. This is the so-called "chaining". The syntax is as follows:

{Expression | filter1 | filter2 | ...}}

Filter may require parameters. Syntax:

{Expression | filter: argument1: argument2 :...}}

For example, the format {1234 | number: 2} uses the filter function of number to filter the number 1234 into a number with two decimal places and the result is: 1,234.00.

Use filter in controller, services, and direves ves

You can use filter in controller, services, and Ves ves.

Therefore, 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 dependency. The injected parameter is a function that uses the value as the first parameter and then uses the second parameter to filter parameters.

The following example uses a filter Filter called filter. This filter can reduce arrays based on sub arrays. You can also apply the tag in the view template, like: {ctrl. array | filter: 'A'}. This will make a full-text search for 'A. However, using filter in the view template will filter each filter again. If the array is large, it will be loaded multiple times.

Therefore, the following example directly calls the filter in the controller. Through this, the controller can call the filter (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');}]);

Result:

All entries: Tobias Jeff Brian Igor James BradEntries that contain an "a": Tobias Brian James Brad

Create custom filters:

Writing your own filter is very simple: you only need to register a new filter factory function in your module. FilterProvider is used internally. This factory function should return a new filter function and take the input value as the first parameter. Any filter parameter is passed as an additional parameter 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 depends on these attributes and executes filter.

Note: The filter name must be a valid angular expression identifier. For example, uppercase or orderBy. Special characters are not allowed for names, such as hyphens and dots. If you want your filter to have a namespace, you can use upper case (myappSubsectionFilterx) or underscore (myapp_subsection_filterx ).

In the following example, filter is used to write 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);}]);

Result:

No filter: helloReverse: ollehReverse + uppercase: OLLEHReverse, filtered in controller: olleh

Stateful filters (Stateful filters)

It is strongly recommended to write stateful filters, because these cannot be optimized with angular, which often leads to performance problems. Many stateful filters convert to stateless filters by exposing hidden states as models and converting them into a filter parameter.

However, if you need to write a stateful filters, you must mark the filter as $ stateful, which means it will be executed once or multiple times in every $ 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: '*'});

Result:

No filter: helloDecorated: *hello*

Next I will write an article about the common filter usage in angularjs.

Articles you may be interested in:
  • Summary of filters. revealTrans. Transition usage
  • Admin generator, filters and I18n
  • Explore PowerShell (12) filter Filters
  • Angularjs summarizes multiple asynchronous request methods
  • $ Apply () method in angularJS
  • How to Use AngularJS to implement HTML page nesting
  • Use AJAX in AngularJS

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.