Created
June 28, 2014 14:15
-
-
Save albertojacini/0d28e9d8f2f9724b34cb to your computer and use it in GitHub Desktop.
Angular groupBy 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
/* | |
* Inspired by http://stackoverflow.com/a/20645945 | |
*/ | |
app.filter('groupBy', ['$parse', function ($parse) { | |
return function (list, group_by) { | |
function addChangedTag (item, field) { | |
item[field + '_CHANGED'] = true; | |
} | |
var filtered = []; | |
var prev_item = null; | |
// loop through each item in the list | |
angular.forEach(list, function (item) { | |
// if not the first item | |
if (prev_item !== null) { | |
// check if any of the group by field changed | |
//force group_by into Array | |
group_by = angular.isArray(group_by) ? group_by : [group_by]; | |
//check each group by parameter | |
for (var i = 0, len = group_by.length; i < len; i++) { | |
if ($parse(group_by[i])(prev_item) !== $parse(group_by[i])(item)) { | |
addChangedTag(item, group_by[i]); | |
} | |
} | |
}// otherwise we have the first item in the list which is new | |
else { | |
for (var i = 0, len = group_by.length; i < len; i++) { | |
addChangedTag(item, group_by[i]); | |
} | |
} | |
filtered.push(item); | |
prev_item = item; | |
}); | |
return filtered; | |
}; | |
}]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment