Last active
August 24, 2017 21:47
-
-
Save krtek/7010022 to your computer and use it in GitHub Desktop.
Simple Angular.js filter to search in array of items.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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