Home > Web Front-end > JS Tutorial > Detailed explanation of using Filters in Angularjs_AngularJS

Detailed explanation of using Filters in Angularjs_AngularJS

WBOY
Release: 2016-05-16 15:11:09
Original
2088 people have browsed it

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

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

The result is:

All entries: Tobias Jeff Brian Igor James Brad
Entries that contain an "a": Tobias Brian James Brad
Copy after login

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

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

The result is:

No filter: hello
Reverse: olleh
Reverse + uppercase: OLLEH
Reverse, filtered in controller: olleh
Copy after login

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

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: '*'});

Copy after login

The result is:

No filter: hello
Decorated: *hello*
Copy after login

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

Related labels:
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