Curriculum
Course: AngularJS
Login

Curriculum

AngularJS

AngularJS Tutorial

0/65
Text lesson

AngularJS Filters

AngularJS Filters

AngularJS offers filters to transform data:

  • currency: Formats a number as currency.
  • date: Formats a date according to a specified format.
  • filter: Selects a subset of items from an array.
  • json: Converts an object to a JSON string.
  • limitTo: Restricts an array or string to a specified number of elements or characters.
  • lowercase: Converts a string to lowercase.
  • number: Formats a number as a string.
  • orderBy: Sorts an array based on an expression.
  • uppercase: Converts a string to uppercase.

Adding Filters to Expressions

Filters can be applied to expressions using the pipe character |, followed by the filter name.

The uppercase filter transforms strings to uppercase.

Example

<div ng-app=”myApp” ng-controller=”personCtrl”>

<p>The name is {{ lastName | uppercase }}</p>

</div>

The lowercase filter converts strings to lowercase.

Example

<div ng-app=”myApp” ng-controller=”personCtrl”>

<p>The name is {{ lastName | lowercase }}</p>

</div>

Adding Filters to Directives

Filters can be applied to directives, such as ng-repeat, by using the pipe character | followed by the filter name.

Example

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

The currency filter converts a number into a currency format.

Example

<div ng-app=”myApp” ng-controller=”costCtrl”>

<h1>Price: {{ price | currency }}</h1>

</div>

The filter Filter

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.

Example

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>

Filter an Array Based on User Input

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.

 
  • Jani
  • Carl
  • Margareth
  • Hege
  • Joe
  • Gustav
  • Birgit
  • Mary
  • Kai

Example

<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>