If you use a factory and want to add a function, you can, for example, add a function to the prototype of the returned element ( DEMO ):
app.factory('Appointment', ['$resource', function($resource) { var Item = $resource('appointments.json',{},{}); Item.prototype.hasServices = function() { if(this.services.length > 0) return true; else return false; }; Item.prototype.partOfDay = function() { if(this.time.split(':')[0] > 12) return "afternoon"; else return "morning"; }; return Item; }]);
And then run it on your resource in the controller:
$scope.appointments = Appointment.query({}, function() { console.log($scope.appointments[0].partOfDay()) });
Or directly in the view inside, for example, ng-repeat:
{{appointment.partOfDay()}}
To answer your last question, I think the above solution is the proper angular method. Once you have functions associated with a particular type of resource, I find it best to add them to the corresponding resource object. Why should you create helper functions in the controller when you need to pass a resource as a parameter and, in addition, functions can be used in several controllers or areas ?!
Marcel gwerder
source share