I'm using AngularJS and I'm trying to get the minimum and maximum values out of a JSON object.
I have a service which calls an API and returns the JSON object:
angular.module('modelLookupServices', ['ngResource']).
factory('Year', function($resource) {
return $resource('/api/years.json/', {},
{
query: {method:'GET', isArray:true}
}
);
});
And in my controller I'm calling this service and using it for different things:
function BrowseCtrl($scope, Year) {
$scope.years = Year.query();
// I want to get the minimum and maximum years out of my model
}
It's fairly simple to implement a min/max function, but my question is where to do it? Should I do it as a service that I can pass the model to and it should return an object with the min/max values? Or should I put it in the controller as a utility function? Or should it be in a completely different place?
I'm trying to follow AngularJS way of clean code and have an implementation with separation of concerns in mind.
The short answer: You can put it wherever it's easiest for you to maintain.
If getting the min/max year is something that you need to do on a regular basis throughout your app, I'd put it in your service. Since services are geared toward inject-able, reusable functionality, it fits.
If it's something that is localized to one part of the app, I'd put it in the controller. Since the controller is basically for manipulation of data in the scope, and you're putting it in the scope, it fits.
It's really your call. But I'd error on the side of readability/maintainability.
EDIT: @RoyTruelove is exactly right... testability can (and should) also be a concern.