Created
March 4, 2015 17:02
-
-
Save bfillmer/1594db4ebb0bba9b00bd to your computer and use it in GitHub Desktop.
Persistent Filter for Angular ng-repeats.
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
'use strict'; | |
angular.module('core') | |
// Persistent filter, runs on any ng-repeat. | |
.filter('PersistentFilter', ['_', 'PersistentFilterStorage', | |
function (_, PersistentFilterStorage) { | |
var pfs = PersistentFilterStorage; | |
return function (items) { | |
var filtered = []; | |
for (var i = 0; i < items.length; i++) { | |
var item = items[i]; | |
if (pfs.returnFilterTruthy(item)) { | |
filtered.push(item); | |
} | |
} | |
return filtered; | |
}; | |
}]) | |
// Persistent filter storage factory. Keeps track of what we are | |
// filtering and why, etc. | |
.factory('PersistentFilterStorage', ['_', | |
function (_) { | |
var service = {}; | |
service.filters = []; | |
// Add filter to storage. | |
service.addFilter = function (key, value) { | |
console.log(key, value); | |
service.filters.push([key, value]); | |
}; | |
// Remove filter from storage. | |
service.removeFilter = function (item) { | |
var i = service.filters.indexOf(item); | |
if (i > -1) { service.filters.splice(i); } | |
}; | |
// Remove all filters from storage. | |
service.clearAllFilters = function () { | |
service.filters = []; | |
}; | |
// Runs on filter loop, returns true if the item matches all of the filter | |
// criteria. | |
service.returnFilterTruthy = function (item) { | |
var truth = true; | |
angular.forEach(service.filters, function (f) { | |
var key = f[0], | |
value = f[1]; | |
if (item.hasOwnProperty(key)) { | |
var check = item[key]; | |
// Array check. | |
if (_.isArray(check) && !_.contains(check, value)) { | |
truth = false; | |
} | |
// String check. | |
if (_.isString(check) && check !== value) { | |
truth = false; | |
} | |
} | |
}); | |
return truth; | |
}; | |
return service; | |
}]) | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment