Search code examples
javascriptangularjsrefactoring

Directive vs. service for refactoring common methods used by multiple controllers in AngularJS


I have a number of different controllers, that all have the same common methods (e.g. save, update etc.). However, each of the controllers performs specific additional actions in those methods. What is the best way to refactor the commonly used code in those methods? Should I use a service for that or write a directive?


Solution

  • If these common methods aren't related to DOM (DOM manipulations, events binding) you should use services. Services are the preferred way to communicate between controllers and wrap common actions.