AngularJS offers filters to transform data:
Filters can be applied to expressions using the pipe character |, followed by the filter name.
The uppercase filter transforms strings to uppercase.
<div ng-app=”myApp” ng-controller=”personCtrl”> <p>The name is {{ lastName | uppercase }}</p> </div> |
The lowercase filter converts strings to lowercase.
<div ng-app=”myApp” ng-controller=”personCtrl”> <p>The name is {{ lastName | lowercase }}</p> </div> |
Filters can be applied to directives, such as ng-repeat, by using the pipe character | followed by the filter name.
The orderBy filter arranges the elements of an array in order.
<div ng-app=”myApp” ng-controller=”namesCtrl”> <ul> <li ng-repeat=”x in names | orderBy:’country'”> {{ x.name + ‘, ‘ + x.country }} </li> </ul> </div> |
The currency filter converts a number into a currency format.
<div ng-app=”myApp” ng-controller=”costCtrl”> <h1>Price: {{ price | currency }}</h1> </div> |
The filter filter selects a subset of an array.
It can only be applied to arrays and returns a new array containing only the matching items.
Return the names that include the letter “i.”
<div ng-app=”myApp” ng-controller=”namesCtrl”> <ul> <li ng-repeat=”x in names | filter : ‘i'”> {{ x }} </li> </ul> </div> |
By applying the ng-model directive to an input field, we can utilize the input field’s value as an expression in a filter.
As you type a letter in the input field, the list will expand or contract based on the match.
<div ng-app=”myApp” ng-controller=”namesCtrl”> <p><input type=”text” ng-model=”test”></p> <ul> <li ng-repeat=”x in names | filter : test”> {{ x }} </li> </ul> </div> |