Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialBrigette Eckert
16,957 PointsServices vs Factories in Angular JS?
Not sure what the difference is. They seem like they do the same thing. Can someone explain?
1 Answer
akak
29,445 PointsThey are pretty similar and in many cases can be used interchangeably.
Here you can read more about that subtle diferences: http://stackoverflow.com/questions/15666048/angularjs-service-vs-provider-vs-factory/15666049#15666049
From my experience I can add that since service is always initiated with the "new" keyword so it returns an object with values and methods. You can do that in factory as well (and in most cases this is what you want to do), but from factory you can also return an function. I found that useful when I wrote my own constructor function, gave it to the factory and then I could create many instances of it when needed.
// in main controller calling a factory constructor function that will create paginate with 5 posts per page
$scope.gallery = new Paginate(5, Model.stateParam(0), $scope.data);
// in single post controller calling the same factory to create pagination for one post only
$scope.posts = new Paginate(1, Model.stateParam(0), $scope.data);
My paginate logic could be created in a service as well but would require a different approach to do so. I've found that this one works the best for my needs :) Just a matter of preference but staying on topic - this kind of initializing function with new would not be possible in a service.
Brigette Eckert
16,957 PointsBrigette Eckert
16,957 PointsOkay it looks like a subtle difference for sure. Thanks :)