Runoob Tutorial ArchiveEnglish

AngularJS filters

AngularJS filters


Filters can be added to expressions and directives using a pipe character (|).


AngularJS filters

AngularJS filters can be used to transform data:

Filters Description
currency Format numbers as currency.
filter Select a subset from an array.
lowercase Format a string to lowercase.
orderBy Sort an array based on an expression.
uppercase Format the string to uppercase.

Add a filter to the expression

A filter can be added to an expression using a pipe character (|).

(For the following two examples, we will use the person controller mentioned in the previous chapter)

uppercaseThe filter formats the string to uppercase:

AngularJS instance

<

div

ng-app=

"myApp"

ng-controller=

"personCtrl"

<

p

Name is

{{ lastName | uppercase }}

<

/p

<

/div

Try it »

lowercaseThe filter formats the string to lowercase:

AngularJS instance

<

div

ng-app=

"myApp"

ng-controller=

"personCtrl"

<

p

Name as

{{ lastName | lowercase }}

<

/p

<

/div

Try it »


currency filter

currencyThe filter formats the number as currency:

AngularJS instance

<

div

ng-app=

"myApp"

ng-controller=

"costCtrl"

<

input

type=

"number"

ng-model=

"quantity"

<

input

type=

"number"

ng-model=

"price"

<

p

Total price =

{{ (quantity * price) | currency }}

<

/p

<

/div

Try it »


Add a filter to the instruction

Filters can be added to instructions using a pipe character (|).

orderByFilters sort arrays based on an expression:

AngularJS instance

<

div

ng-app=

"myApp"

ng-controller=

"namesCtrl"

<

ul

 

<

li

ng-repeat=

"x in names | orderBy:'country'"

   

{{ x.name + ', ' + x.country }}

 

<

/li

<

/ul

<

/div

Try it »


Filter input

Input filters can be added to a prompt using a pipe character (|) followed by a filter, a colon, and a model name.

filterThe filter selects a subset from an array:

AngularJS instance

<

div

ng-app=

"myApp"

ng-controller=

"namesCtrl"

<

p

<

input

type=

"text"

ng-model=

"test"

<

/p

<

ul

 

<

li

ng-repeat=

"x in names | filter:test | orderBy:'country'"

   

{{ (x.name | uppercase) + ', ' + x.country }}

 

<

/li

<

/ul

<

/div

Try it »


Custom filter

The following example customizes a filterreversereverses a string:

AngularJS instance

var

app

=

angular

.

module

(

'

myApp

'

,

[

]

)

;

app

.

controller

(

'

myCtrl

'

,

function

(

$

scope

)

{

$

scope

.

msg

=

"

Runoob

"

;

}

)

;

app

.

filter

(

'

reverse

'

,

function

(

)

{

//

Dependencies can be injected

return

function

(

text

)

{

return

text

.

split

(

"

"

)

.

reverse

(

)

.

join

(

"

"

)

;

}

}

)

;

Try it »