Skip to content

Instantly share code, notes, and snippets.

@krtek
Last active August 24, 2017 21:47
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save krtek/7010022 to your computer and use it in GitHub Desktop.
Simple Angular.js filter to search in array of items.
app.controller 'ListController', ($scope, $filter) ->
$scope.search = {}
$scope.all_data = [
{title: 'Three men on the bummel', 'author': 'Jerome Klapka Jerome', meta: {isbn: 2234}}
{title: 'Three men on a boat', 'author': 'Jerome Klapka Jerome', meta: {isbn: 1234}}
{title: 'Three musketeers', 'author': 'Alexandre Dumas', meta: {isbn: 4566}}
{title: 'Four tank men and a dog', 'author': 'Janusz Przymanowsky', meta: {isbn: 1222}}
]
$scope.$watch("search.query", ( ->
#Object is resource
$scope.display_data = $filter("matchAllToProperties")($scope.all_data, $scope.search.query,
['prev_state','next_state'])
), true)
$scope.clearSearch = () ->
$scope.search = {}
angular.module("filters", [])
.filter('matchAllToProperties', () ->
return (input, query, exclude) ->
if not input or not query
return input
bits = (b.toLowerCase() for b in query.split(' ') when b isnt ' ')
filtered = []
for item in input
item_copy = angular.copy(item)
#Remove fields in which we don't want to search
_.each(exclude, (prop)-> delete item_copy[prop])
json = JSON.stringify(item_copy).toLowerCase()
if _.every(bits, (bit) -> json.indexOf(bit) > 0)
filtered.push(item)
return filtered
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment