angularjs where filter
Update The latest release of angular adds a comparator argument to the filter
filter, which can be used to achieve what the code below does (just pass true
, see https://github.com/angular/angular.js/blob/master/src/ng/filter/filter.js#L35)
Often we need to filter objects by specific attributes. Angularjs comes with a limited filter
filter, but we can write our own:
module.filter 'where', ->
matchProperty = (obj, key, shouldEqual) ->
value = obj[key]
value = value.call(obj) if angular.isFunction(value)
value == shouldEqual
(input, properties) ->
r = input.slice(0)
for k, v of properties
i = 0
while i < r.length
if matchProperty(r[i], k, v) then i++ else r.splice(i, 1)
return r unless r.length
r
Now we can filter:
li ng-repeat="l in locations | where:{type:'country'}"
Written by Gleb Mazovetskiy
Related protips
1 Response
@glebby, you can write input[...]
instead of input.slice(0)
ā
I miss you,
aaron
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Angularjs
Authors
Related Tags
#angularjs
Sponsored by #native_company# ā Learn More
#native_title#
#native_desc#