MOCKSTACKS
EN
Questions And Answers

More Tutorials









Angular Custom filters

Use a filter in a controller, a service or a filter


You will have to inject $filter:
angular

 .module('filters', [])
 .filter('percentage', function($filter) {
 return function (input) {
 return $filter('number')(input * 100) + ' %';
 };
 });


Create a filter with parameters


By default, a filter has a single parameter: the variable it is applied on. But you can pass more parameter to the function:

angular

.module('app', [])
 .controller('MyController', function($scope) {
 $scope.example = 0.098152;
 })
 .filter('percentage', function($filter) {
 return function (input, decimals) {
 return $filter('number')(input * 100, decimals) + ' %';
 };
 });


Now, you can give a precision to the percentage filter:

<span ng-controller="MyController">{{ example | percentage: 2 }}</span>
=> "9.81 %"


... but other parameters are optional, you can still use the default filter:

<span ng-controller="MyController">{{ example | percentage }}</span>
=> "9.8152 %"


Simple filter example



Filters format the value of an expression for display to the user. They can be used in view templates, controllers or services. This example creates a filter (addZ) then uses it in a view. All this filter does is add a capital 'Z' to the end of the string.

example.js

angular.module('main', [])
 .filter('addZ', function() {
 return function(value) {
 return value + "Z";
 }
 })
 .controller('MyController', ['$scope', function($scope) {
 $scope.sample = "hello";
 }])

example.html

Inside the view, the filter is applied with the following syntax: { variable | filter}. In this case, the variable we defined in the controller, sample, is being filtered by the filter we created, addZ.

<div ng-controller="MyController">
 <span>{{sample | addZ}}</span>
</div>
Output
helloZ



Conclusion

In this page (written and validated by ) you learned about AngularJS Custom filters . What's Next? If you are interested in completing AngularJS tutorial, your next topic will be learning about: AngularJS Constants.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.