If you want to use the actual Angular Service (not factory, or provider), then all you have to do is the following to create something the Angular way.
mod.service ('sharedService', function() {
function daysInMonth(month,year) {
return new Date(year, month+1,0).getDate();
}
});
// Would turn into
mod.service("sharedService", function(){
this.daysInMonth(month, year){
return new Date(year, month + 1, 0).getDate();
}
});
You should not RETURN from a service unless you NEED to override the default THIS object that will be created when the service is NEW'ED. In that case, you can return an Object Literal, Function Definition, Array, most Objects excluding any primitives. Just assure you ask the question "why do I need to override the default behavior?"
That's really the entire point of a service. When you inject the SERVICE Angular will NEW the function you pass, thus returning it to you as described. In your case, the service will be exactly what you need. Angular will build the Service just once, and the new sharedService function result will be available throughout your application, but only when the service is DI'd at least once somewhere in your application. If you don't DI it, then the service will never be created as it is lazily loaded (Factory and Service).
If you find you really want to return something, (although you CAN do it in a service), the appropriate place would be in an Angular Factory. In fact, if you DON'T return from a Factory you will get a nice little notice
ERROR: Provider 'sharedService' must return a value from $get factory method.
NOTE: where the $get function is the second argument of the service function definition.
mod.factory("sharedService", function(){
function daysInMonth(month, year){
return new Date(year, month + 1, 0).getDate();
}
return {
daysInMonth: daysInMonth
}
// Or you could do this...
return daysInMonth;
});
When using the Angular Factory you no longer get a NEW'ED function, which is why a return must be created.