Created
March 6, 2015 17:13
-
-
Save alexmiddeleer/7f65c03370b23c5038af to your computer and use it in GitHub Desktop.
Angular advanced search filter
This file contains 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
var myApp = angular.module('myApp', []); | |
myApp.controller('ctrl', function ($scope) { | |
$scope.items = [{ | |
name:'foo', | |
color:'red' | |
},{ | |
name:'bar', | |
color:'blue' | |
},{ | |
name:'baz', | |
color:'green' | |
}]; | |
$scope.searchNames = true; | |
$scope.searchColors = true; | |
$scope.$watch('searchColors', function(){ | |
$scope.searchKeys = [ $scope.searchNames ? 'name' : null, $scope.searchColors ? 'color' : null ]; | |
}); | |
$scope.$watch('searchNames', function(){ | |
$scope.searchKeys = [ $scope.searchNames ? 'name' : null, $scope.searchColors ? 'color' : null ]; | |
}); | |
}); | |
myApp.filter('advancedSearch', function($filter) { | |
return function(data, keys, query) { | |
results = []; | |
if( !query ){ | |
return data; | |
} else { | |
angular.forEach( data, function( obj ){ | |
var matched = false; | |
angular.forEach( keys, function( key ){ | |
if( obj[key] ){ | |
// match values using angular's built-in filter | |
if ($filter('filter')([obj[key]], query).length > 0){ | |
// don't add objects to results twice if multiple | |
// keys have values that match query | |
if( !matched ) { | |
results.push(obj); | |
} | |
matched = true; | |
} | |
} | |
}); | |
}); | |
} | |
return results; | |
}; | |
}); |
This file contains 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
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> | |
<html ng-app="myApp"> | |
<div ng-controller="ctrl"> | |
<input type='checkbox' ng-model='searchNames'>search names</input> | |
<input type='checkbox' ng-model='searchColors'>search colors</input> | |
<input type='text' ng-model='query'>search objects</input> | |
<ul> | |
<li ng-repeat="item in items | advancedSearch : searchKeys : query"> | |
<span style="color:{{item.color}}">{{item.name}}</span> | |
</li> | |
</ul> | |
</div> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
results is undefined