Bunch of useful filters for AngularJS (with no external dependencies!)

Angular 2 version is now available: ng-pipes
Table of contents:
Get Started
(1) You can install angular-filter using 4 different methods:
- clone & build this repository
- via Bower: by running
$ bower install angular-filter
from your terminal - via npm: by running
$ npm install angular-filter
from your terminal - via cdnjs http://www.cdnjs.com/libraries/angular-filter
(2) Include angular-filter.js
(or angular-filter.min.js
) in your index.html
, after including Angular itself.
(3) Add 'angular.filter'
to your main module's list of dependencies.
When you're done, your setup should look similar to the following:
... ... ...
Collection
concat
Concatenates an array/object into another one.
{ $scopearray = a: 1 a: 2 ; $scopeobject = 0: a: 3 1: a: 4 ;}
{{ elm.a }} <!--result:1 2 3 4--> {{ elm.a }} <!--result:3 4 1 2-->
unique
Remove duplicates from an array/object.
If a string is provided, it will filter out duplicates using the provided expression.
Usage: collection | unique: 'property'
aliases: uniq
{ $scopeorders = id:1 customer: name: 'John' id: 10 id:2 customer: name: 'William' id: 20 id:3 customer: name: 'John' id: 10 id:4 customer: name: 'William' id: 20 id:5 customer: name: 'Clive' id: 30 ;}
Ex: Filter by customer.id
Customer list: {{ order.customer.name }} , {{ order.customer.id }} <!-- result:All customers list:John 10William 20Clive 30
filterBy
Filter a collection by a specific property.
Usage: collection | filterBy: [prop, nested.prop, etc..]: search: strict[optional]
Note: You can even use compound properties (e.g: |filterBy: [property + property]: model
)
$scopeusers = id: 1 user: first_name: 'Rob' last_name: 'John' mobile: 4444 id: 2 user: first_name: 'John' last_name: 'Wayne' mobile: 3333 id: 3 user: first_name: 'Rob' last_name: 'Johansson' mobile: 2222 id: 4 user: first_name: 'Mike' last_name: 'Terry' mobile: 1111 ;
Return users whose id is 1
<!--search only by id --> {{ user.id }} : {{ user.first_name }} {{ user.last_name }}<!--result: 1: Rob John-->
Return users whose first name or last name is 'John' (uses nested properties).
<!--search by first_name and last_name --> {{ user.first_name }} {{ user.last_name }}<!--result: 1: Rob John 2: John Wayne-->
Return users whose full name is
<!--search by full name --> {{ user.id }}: {{ user.first_name }} {{ user.last_name }}<!--result: 1: Rob John 3: Rob Johannson-->
first
Gets the first element(s) of a collection.
If an expression is provided, it will only return elements whose expression is truthy.
Usage: See below
$scopeusers = id: 1 name: first: 'John' last: 'Wayne' id: 2 name: first: 'Mike' last: 'Johannson' id: 3 name: first: 'William' last: 'Kyle' id: 4 name: first: 'Rob' last: 'Thomas' ;
Returns the first user.
{{ users | first }}<!--result:{ id: 1, name: { first: 'John', last: 'Wayne' } }-->
Returns the first user whose first name is 'Rob' and last name is 'Thomas'
<!-- collection | first: expression -->{{ users | first: 'name.first === \'Rob\' && name.last === \'Thomas\'' }}<!--result:[ { id: 4, name: { first: 'Rob', last: 'Thomas' } } ]-->
Return the first two users
<!-- collection | first: n --> {{ user.name.first }}<!--result:JohnMike-->
Return the first two users with even id
<!-- collection | first: n: expression --> {{ user.name }}<!--result:MikeRob
last
Gets the last element or last n elements of a collection,
if expression is provided, is returns as long the expression return truthy
Usage: See below
$scopeusers = id: 1 name: first: 'foo' last: 'bar' id: 2 name: first: 'baz' last: 'bar' id: 3 name: first: 'bar' last: 'bar' id: 4 name: first: 'lol' last: 'bar' ;
{{ users | last }}<!--result:{ id: 4, name: { first: 'lol', last: 'bar' } }
<!-- collection | last: expression -->{{ users | last: 'name.last === \'bar\'' }}<!--result:[ { id: 4, name: { first: 'lol', last: 'bar' } } ]
<!-- collection | last: n --> {{ user.name }}<!--result:barlol
<!-- collection | last: n: expression --> {{ user.name }}<!--result:bazlol
flatten
Flattens a nested array (the nesting can be to any depth).
If you pass shallow, the array will only be flattened a single level
Usage: collection | flatten: shallow[optional]
$scopeweirdArray = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15;
{{ elm }},<!--result:1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
join
Joins the contents of a collection into a string.
By default, it will join elements with a single space, but you can provide your own delimiter.
Usage: collection | join:', '
Example:
$scopenames = 'John' 'Sebastian' 'Will' 'James';
{{ names | join:', ' }}<!-- Will print "John, Sebastian, Will, James" -->
fuzzy
fuzzy string searching(approximate string matching). Read more
note: use fuzzyBy to filter by one property to improve performance
Usage: collection | fuzzy: search: caseSensitive[optional]
$scopebooks = title: 'The DaVinci Code' author: 'F. Scott Fitzgerald' title: 'The Great Gatsby' author: 'Dan Browns' title: 'Angels & Demons' author: 'Dan Louis' title: 'The Lost Symbol' author: 'David Maine' title: 'Old Man\'s War' author: 'Rob Grant' ;
{{ book.title }}<!--case sensitive--> {{ book.title }}
fuzzyBy
fuzzy string searching(approximate string matching) by property(nested to). Read more
Usage: collection | fuzzyBy: 'property': search: caseSensitive[optional]
$scopebooks = title: 'The DaVinci Code' title: 'The Great Gatsby' title: 'Angels & Demons' title: 'The Lost Symbol' title: 'Old Man\'s War' ;
{{ book.title }}<!--case sensitive--> {{ book.title }}
groupBy
Create an object composed of keys generated from the result of running each element of a collection,
each key is an array of the elements.
Usage: (key, value) in collection | groupBy: 'property'
or ... | groupBy: 'nested.property'
$scopeplayers = name: 'Gene' team: 'alpha' name: 'George' team: 'beta' name: 'Steve' team: 'gamma' name: 'Paula' team: 'beta' name: 'Scruath' team: 'gamma';
Group name: {{ key }} player: {{ player.name }} <!-- result: Group name: alpha * player: Gene Group name: beta * player: George * player: Paula Group name: gamma * player: Steve * player: Scruath
countBy
Create an object composed of keys generated from the result of running each element of a collection,
each key is the count of objects in each group
Usage: (key, value) in collection | countBy: 'property'
or ... | countBy: 'nested.property'
$scopeplayers = name: 'Gene' team: 'alpha' name: 'George' team: 'beta' name: 'Steve' team: 'gamma' name: 'Paula' team: 'beta' name: 'Scruath' team: 'gamma';
Group name: {{ key }}, length: {{ value }}<!-- result: Group name: alpha, length: 1 Group name: beta, length: 2 Group name: gamma, length: 2
chunkBy
Collect data into fixed-length chunks or blocks
Usage: (key, value) in collection | chunkBy: 'n': fill-value(optional)
$scopearray = 1 2 3 4 5 6;
Block: {{ block }}<!-- result: Block: [1, 2] Block: [3, 4] Block: [5, 6]--> Block: {{ block }}<!-- result: Block: [1, 2, 3, 4] Block: [5, 6, 0, 0]
defaults
defaultsFilter
allows to specify a default fallback value for properties that resolve to undefined.
Usage: col in collection | defaults: fallback
$scopeorders = id:1 destination: zip: 21908 name: 'Ariel M' id:2 name: 'John F' id:3 destination: zip: 45841 id:4 destination: zip: 78612 name: 'Danno L' ;$scopefallback = name: 'Customer name not available' destination: zip: 'Pickup' ;
id: {{ order.id }}, name: {{ order.name }}, shipping address: {{ order.destination.zip }}<!--Results:* id: 1, name: Ariel M, shipping address: 21908* id: 2, name: John F, shipping address: Pickup* id: 3, name: Customer name not available, shipping address: 45841* id: 4, name: Danno L, shipping address: 78612
Note: defaultsFilter
change the source object.
Why? if we not change the source object, it's actually means we gonna return new object(copy operation) each digest cycle.
And it will cause adverse memory and performance implications.
How to avoid it? see below
//We copy it once, and it's really cheaper$scopeordersWithFallback = angular;
<!-- ..... -->
where
comparison for each element in a collection to the given properties object,
returning an array of all elements that have equivalent property values.
$scopecollection = id: 1 name: 'foo' id: 1 name: 'bar' id: 2 name: 'baz'
{{ obj.name }}<!-- result: foo bar--> {{ obj.name }}<!-- result: foo -->
omit
return collection without the omitted objects(by expression).
usage: collection | omit: expression
example 1:
$scope { return !elm % 2;}
{{ num }},<!--result1, 3, 5
example 2:
$scopecollection = id: 1 user: name: 'foo' id: 2 user: name: 'bar' id: 3 user: name: 'baz'
id: {{ obj.id }}, name: {{ obj.user.name }}<!--result:id: 1, name: foo
pick
return collection composed of the picked objects(by expression).
usage: collection | pick: expression
example 1:
$scope { return !elm % 2;}
{{ num }},<!--result2, 4, 6
example 2:
$scopecollection = id: 1 user: name: 'foo' id: 2 user: name: 'bar' id: 3 user: name: 'baz'
id: {{ obj.id }}, name: {{ obj.user.name }}<!--result:id: 2, name: barid:3, name: baz
remove
Returns a new collection of removed elements.
$scopefoo = name: 'foo' ;$scopecollection = name: 'bar' $scopefoo null 1;
{{ obj }}<!-- result: { "name": "bar" }
removeWith
comparison for each element in a collection to the given properties object,
returning an array without all elements that have equivalent property values.
$scopecollection = id: 1 name: 'foo' id: 1 name: 'bar' id: 2 name: 'baz'
{{ obj.name }}<!-- result: baz--> {{ obj.name }}<!-- result: bar baz
searchField
if you want to use the filter in angular and want to filter for multiple values
so searchField filter return new collection with property called searchField
support nested properties with dot notation i.e: collection | searchField: 'prop': 'nested.prop'
$scopeusers = first_name: 'Sharon' last_name: 'Melendez' first_name: 'Edmundo' last_name: 'Hepler' first_name: 'Marsha' last_name: 'Letourneau' ;
{{ user.first_name }} {{ user.last_name }}<!-- so now you can search by full name -->
after
get a collection(array or object) and specified count, and returns all of the items in the collection after the specified count.
$scopecollection = name: 'foo' name: 'bar' name: 'baz' name: 'zap' ;
{{ col.name }}<!--result: baz zap-->
afterWhere
get a collection and properties object, and returns all of the items, in the collection after the first that found with the given properties, including it.
$scopeorders = id: 1 customer: name: 'foo' date: 'Tue Jul 15 2014' id: 2 customer: name: 'foo' date: 'Tue Jul 16 2014' id: 3 customer: name: 'foo' date: 'Tue Jul 17 2014' id: 4 customer: name: 'foo' date: 'Tue Jul 18 2014' id: 5 customer: name: 'foo' date: 'Tue Jul 19 2014' ;
order: {{ order.id }}, {{ order.date }}<!--result: order: 3, Tue Jul 17 2014 order: 4, Tue Jul 18 2014 order: 5, Tue Jul 19 2014-->
before
get a collection(array or object) and specified count, and returns all of the items in the collection before the specified count.
$scopecollection = name: 'foo' name: 'bar' name: 'baz' name: 'zap' ;
{{ col.name }}<!--result: foo bar-->
beforeWhere
get a collection and properties object, and returns all of the items, in the collection before the first that found with the given properties, including it.
$scopeorders = id: 1 customer: name: 'foo' date: 'Tue Jul 15 2014' id: 2 customer: name: 'foo' date: 'Tue Jul 16 2014' id: 3 customer: name: 'foo' date: 'Tue Jul 17 2014' id: 4 customer: name: 'foo' date: 'Tue Jul 18 2014' id: 5 customer: name: 'foo' date: 'Tue Jul 19 2014' ;
order: {{ order.id }}, {{ order.date }}<!--result: order: 1, Tue Jul 15 2014 order: 2, Tue Jul 16 2014 order: 3, Tue Jul 17 2014-->
reverse
Reverse the order of the elements in a collection
$scopeusers = id: 1 name: 'bazzy' id: 2 name: 'dazzy' id: 3 name: 'lazzy' ;
user: {{ user.id }}, {{ user.name }}<!--result: user: 3, lazzy user: 2, dazzy, user: 1, bazzy-->
isEmpty
get collection or string and return if it empty[Boolean]
<!-- ..... --><!--some replacer msg--> no content to show
contains
Checks if given expression(or value) is present in one or more object in the collection
Usage: collection | contains: 'expression'
Aliases: some
example 1:
$scopearray = 1234;
...
example 2:
$scopecollection = user: id: 1 name: 'foo' user: id: 2 name: 'bar' user: id: 3 name: 'baz' ;
...<!--result: true
every
Checks if given expression(or value) return truthy value for all members of a collection
Usage: collection | every: 'expression'
example 1:
$scopearray = 1111;
...<!--result: true
example 2:
$scopecollection = user: id: 4 name: 'foo' user: id: 6 name: 'bar' user: id: 8 name: 'baz' ;
...<!--result: true
xor
Exclusive or between two collections
Usage: collection1 | xor: collection2: expression[optional]
Example1:
{{ elm }}<!--result:1 4 5
Example2:
$scopeusers1 = id: 0 details: first_name: 'foo' last_name: 'bar' id: 1 details: first_name: 'foo' last_name: 'baz' id: 2 details: first_name: 'foo' last_name: 'bag' ;$scopeusers2 = id: 3 details: first_name: 'foo' last_name: 'bar' id: 4 details: first_name: 'foo' last_name: 'baz' ;
{{ user.id }}<!--result:1 2 3 4 5--> {{ user.id }}, {{ user.details.first_name }} {{ user.details.last_name }}<!--result:2, foo bag
toArray
Convert objects into stable arrays.
Usage: object | toArray: addKey[optional]
if addKey set to true, the filter also attaches a new property $key to the value containing the original key that was used in the object we are iterating over to reference the property
{{ elm.name }}
map
Returns a new collection of the results of each expression execution.
Usage: collection | map: expression
Example1:
$scope { return elm/2}
{{ i }}<!--result:0.5, 1, 1.5, 2, 2.5
pluck
Used map
$scopeusers = id:1 user: name: 'Foo' id:1 user: name: 'Bar' id:1 user: name: 'Baz' ;
{{ name }}<!--result:FooBarBaz
range
Return a new collection from a given length, start, increment, and callback
By default start is 0, increment is 1, and callback is null.
Usage: collection | range: length:start:increment:callback
[{{i}},]<!--result:[0,1,2,]-->
[{{i}},]<!--result:[10,11,12,13,14,15,16,17,18,19,]-->
[{{ i }},]<!--result:[5, 7, 9, 11, 13, 15, 17, 19, 21, 23]-->
[{{ i }},]<!--result:[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24]-->
$scope { return i * 2;}
[{{ i }},]<!--result:[8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48]-->
String
ucfirst
ucfirstFilter get string as parameter and return it capitalized
{{ 'foo bar baz' | ucfirst }} <!--result:Foo Bar Baz-->
uriEncode
get string as parameter and return encoded uri
Link
uriComponentEncode
get string as parameter and return encoded uri component
Link
slugify
Transform text into a URL slug. Replaces whitespaces, with dash("-"), or given argument
Link<!--replace with given argument-->Link<!--result:<a ng-href="http://domain.com/fetch/some-string-with-spaces">Link</a> <a ng-href="http://domain.com/fetch/some=string=with=spaces">Link</a>-->
latinize
Remove accents/diacritics from a string
{{ 'Sòme strÏng with Âccénts' | latinize }}<!--result: Some strIng with Accents-->
startsWith
return whether string starts with the starts parameter.
usage: string | startsWith: 'start': case-sensitive[optional]
{{ 'Lorem ipsum' | startsWith: 'lorem' }} {{ 'Lorem Ipsum' | startsWith: 'lorem': true }} <!--result: true false
endsWith
return whether string ends with the ends parameter.
usage: string | endsWith: 'ends': case-sensitive[optional]
{{ 'image.JPG' | endsWith: '.jpg' }} {{ 'image.JPG' | endsWith: '.jpg': true }} <!--result: true false
stripTags
strip out html tags from string
**Important: this filter jobs it's not to replace ng-bind-html directive, it's only for tiny plain text
$scopetext = '<p class="paragraph">Lorem Ipsum is simply dummy text of the printing...</p>';
{{ text | stripTags }}<!--result:Lorem Ipsum is simply dummy text of the printing...-->
stringular
get string with {n} and replace match with enumeration values
{{ 'lorem {0} dolor {1} amet' | stringular:'ipsum':'sit' }}{{ '{3} {0} dolor {1} amet' | stringular:'ipsum':'sit':null:'lorem' }} <!-- result:<p>lorem ipsum dolor sit amet</p><p>lorem ipsum dolor sit amet</p>--> {{ 'lorem {0} dolor sit amet' | stringular }}<!--result:<p>lorem {0} dolor sit amet</p>
phoneUS
Format a string or a number into a us-style phone number
{{ 1234567890 | phoneUS }} <!--result:<p>(123) 456-7890</p>
truncate
truncates a string given a specified length, providing a custom string to denote an omission.
usage: | truncate: [length]: [suffix-optional]: [preserve-optinal]
$scopetext = 'lorem ipsum dolor sit amet';
<!--should not cut words in the middle if preserve is true-->{{ text | truncate: 7: '...': true }} {{ text | truncate: 13: '...' }} <!--should not touch string that shorter than the provided length -->{{ text | truncate: 50: '...' }} <!--result:lorem ipsum...lorem ipsum d...lorem ipsum dolor sit amet
split
truncates a string given a specified length, providing a custom string to denote an omission.
usage: | split: [delimiter]: [skip-optional]
$scopetext = 'lorem ipsum dolor sit amet';
{{ text | split: ' ' }} {{ text | split: ' ': 2}} <!--result:['lorem', 'ipsum', 'dolor', 'sit', 'amet']['lorem ipsum dolor', 'sit', 'amet']
reverse
Reverses a string
$scopetext = 'lorem ipsum dolor sit amet';
{{ text | reverse }}<!--result:tema tis rolod muspi merol
wrap
Wrap a string with another string
usage: string | wrap: string: string[optional]
{{ 'foo' | wrap: '/' }}{{ 'foo' | wrap: '{{': '}}' }}<!--result:/foo/{{foo}}
trim
Strip whitespace (or other characters) from the beginning and end of a string
usage: string | trim: chars[optional]
{{ ' foo ' | trim }}{{ 'foobarfoo' | trim: 'foo' }}<!--result:foobar
ltrim
Strip whitespace (or other characters) from the beginning of a string
usage: string | ltrim: chars[optional]
{{ 'barfoobar' | ltrim: 'bar' }}<!--result:foobar
rtrim
Strip whitespace (or other characters) from the end of a string
usage: string | rtrim: chars[optional]
{{ 'barfoobar' | rtrim: 'bar' }}<!--result:barfoo
repeat
Repeats a string n times
Usage: string | repeat: n: separator[optional]
{{ 'foo' | repeat: 3: '-' }}<!--repeat:foo-foo-foo
test
Test if a string match a pattern
Usage: string | test: pattern: flag[optional]
{{ '15/12/2003' | test: '^[0-9]{2}[/]{1}[0-9]{2}[/]{1}[0-9]{4}$': 'i' }}{{ '0123456' | test: '\\D': 'i' }}<!--result:truetrue
match
Return an array of matched element in a string
Usage: string | match: pattern: flag[optional]
{{ '15/12/2003' | match: '\\d+': 'g' }}<!--result:['15', '12', '2003']
Math
max
max find and return the largest number in a given array.
if an expression
is provided, will return max value by expression.
Usage: array | max: expression[optional]
$scopeusers = user: score: 988790 user: score: 123414 user: rank : 988999 user: score: 987621 ;
{{ [1,2,3,4,7,8,9] | max }} {{ users | max: 'user.score || user.rank' }}<!--result:* 9* { user: { rank : 988999 } }
min
min find and return the lowest number in a given array.
if an expression
is provided, will return min value by expression.
Usage: array | min: expression[optional]
$scopeusers = user: score: 988790 user: score: 123414 user: score: 987621 ;
{{ [1,2,3,4,7,8,9] | min }} {{ users | min: 'user.score' }}<!--result:* 1* { user: { score: 123414 } }
abs
Returns the absolute value of a number
Usage: number | string
The absolute value of {{val}} is {{val | abs}}<!--result:* The absolute value of -1.2 is 1.2* The absolute value of 2.3 is 2.3* The absolute value of -3.4 is 3.4* The absolute value of '4.5' is 4.5
percent
Percentage between two numbers
Usage: number | percent: total: round[optional]
, round by default false.
{{ 23 | percent: 500 }}{{ 23 | percent: 500: true }}<!--result:4.64
radix
Converting decimal numbers to different bases(radix)
Usage: number | radix: base
{{ 8 | radix: 2 }}{{ 32586 | radix: 16 }}<!--result:10007F4A
sum
Sum up all values within an array
Usage: array | sum: initial-value[optional]
{{ [2,3,5] | sum }}{{ [2,3,5] | sum: 10 }}<!--result1020
degrees
Converts radians into degrees
Usage: radians | degrees: round-to-decimal
,
{{ 0.785398 | degrees: 0 }}{{ -1.57 | degrees: 3 }}<!--result45-89.954
radians
Converts degrees into radians
Usage: degrees | radians: round-to-decimal
,
{{ 45 | radians: 2 }}{{ 180 | radians: 5 }}<!--result0.793.14159
shortFmt
Converts numbers into formatted display
Usage: number | shortFmt: round-to-decimal
,
{{ 45000 | shortFmt: 0 }}{{ 18234822 | shortFmt: 1 }}<!--result45 k18.2 m
byteFmt
Converts bytes into formatted display
Usage: number | byteFmt: round-to-decimal
,
{{ 1998 | byteFmt: 2 }}{{ 1339234901 | byteFmt: 5 }}<!--result1.95 KB1.24726 GB
kbFmt
Converts kilobytes into formatted display
Usage: number | kbFmt: round-to-decimal
,
{{ 1024 | kbFmt: 0 }}{{ 1049901 | kbFmt: 5 }}<!--result1 MB1.00126 GB
Boolean
Used for boolean expression in chaining filters
isGreaterThan
aliases: >
<!--or: -->
isGreaterThanOrEqualTo
aliases: >=
<!--or: -->
isLessThan
aliases: <
<!--or: -->
isLessThanOrEqualTo
aliases: <=
<!--or: -->
isEqualTo
aliases: ==
<!--or: -->
isNotEqualTo
aliases: !=
<!--or: -->
isIdenticalTo
aliases: ===
<!--or: -->
isNotIdenticalTo
aliases: !==
<!--or: -->
Changelog
0.5.7
- fix issue #119
0.5.6
- fix issue #145
0.5.5
- add
range
andchunk-by
filters - fix issue #139
0.5.4
- add
match
andtest
filters
0.5.3
- add
latinize
filter
0.5.1
min
andmax
can get a property as an argument.- improve
slugify
filter. - refactor
filterWatcher
(memoize), now it works like a charm. - refactor
groupBy
now it can get be chain with other filters
0.4.9
- fix issue #38 with reverseFilter
0.4.8
- add defaultsFilter
- improve docs, tests
0.4.7
- add condition filters set.
TODO
- Add project website on branch gh-pages, see Github-help
Contributing
- If you planning add some feature please create issue before.
- Don't forget about tests.
Clone the project:
$ git clone$ npm install$ bower install
Run the tests:
$ grunt test