To get an idea of what the controller code reflects, here is a screenshot:
Basically, the idea is that you print out a list of football players which you can then filter by their name, price, field position, and team. I'm not sure whether it's better to handle all the scope logic within a single controller, or break it down into separate controllers, isolating the filters from the player list, pagination, and so on. I'm currently going with the single controller approach, and here's what I have:
app.controller('playersController', function($scope, $filter, minMax, buildOptions, PlayersModel, TeamsModel, CommonValues){
$scope.basehref = CommonValues.getBaseHref();
$scope.imgbase = CommonValues.getImgBase();
$scope.players = PlayersModel;
$scope.teams = TeamsModel;
$scope.predicate = 'team.name';
$scope.minMax = minMax($scope.players);
$scope.filters = { // filter model
searchString: '', // string input from user
selectedTeam: {}, // selected team
selectedTeamMs: [], // selected teams from multiselect
roles: {
1: true, // forward
2: true, // defense
3: true, // midfield
4: true // goalie
},
slider: { // set up boundaries for slider filter
min: $scope.minMax[0],
max: $scope.minMax[1],
step: 10000
},
pagination: { // set up pagination
totalItems: $scope.players.length,
currentPage: 1,
maxSize: 5,
pages: buildPages()
}
};
var cache = $scope.players; // save original player model for later use
/**********
* Watchers
**********/
// watch for filter model changes, start filtering
$scope.$watch('filters', function(newVal, oldVal){
if (newVal !== oldVal || newVal.id !== oldVal.id || newVal.length !== oldVal.length) {
var result;
result = $filter('textFilter')(cache, $scope.filters); // filter by phrase
result = $filter('roleFilter')(result, $scope.filters); // filter by field position
result = $filter('teamFilter')(result, $scope.filters.selectedTeamMs); // filter by team
$scope.players = result;
}
}, true);
/***********
* Scope API
***********/
// pagination logic
$scope.changePage = function(newVal, oldVal) {
var maxSize = $scope.filters.pagination.maxSize;
var offset = maxSize * oldVal;
var result = [];
if (newVal < oldVal) offset = (maxSize * newVal) - maxSize;
for (var i = 0; i < cache.length; i++) {
if (i >= offset) result.push(cache[i]);
}
$scope.players = result;
};
/****************
* Helper methods
****************/
function buildPages() {
return null;
}
});
Is it ok to encapsulate all the logic into that one controller, including helper methods, and so on, or should I refactor?