I\'m new to Angular and would like to learn the best way to handle a problem. My goal is to have a reusable means to create group by headers. I created a solution which wor
EDIT: here's a custom filter approach. Groups is created by a filter function in scope to generate array of groups from current list. Adding/deleting list items will bind update of the group array as it is reset every digest cycle.
HTML
{{group}}
- {{item.whatever}}
JS
var app=angular.module('myApp',[]);
app.filter('groupby', function(){
return function(items,group){
return items.filter(function(element, index, array) {
return element.GroupByFieldName==group;
});
}
})
app.controller('TestGroupingCtlr',function($scope) {
$scope.MyList = [{ GroupByFieldName: 'Group 1', whatever: 'abc'},
{GroupByFieldName: 'Group 1',whatever: 'def'},
{GroupByFieldName: 'Group 2',whatever: 'ghi' },
{GroupByFieldName: 'Group 2',whatever: 'jkl'},
{GroupByFieldName: 'Group 2',whatever: 'mno' }
];
$scope.getGroups = function () {
var groupArray = [];
angular.forEach($scope.MyList, function (item, idx) {
if (groupArray.indexOf(item.GroupByFieldName) == -1)
groupArray.push(item.GroupByFieldName)
});
return groupArray.sort();
}
})
DEMO