Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save spacecowb0y/9188456 to your computer and use it in GitHub Desktop.
Save spacecowb0y/9188456 to your computer and use it in GitHub Desktop.

WHEN TO USE DIRECTIVES, CONTROLLERS, OR SERVICES IN ANGULAR JS

SERVICES

Whenever we want to share data across domains. Additionally, thanks to Angular’s dependency injection system, this is both very easy to do and very clean.

module.service( 'Book', [ '$rootScope', function( $rootScope ) {
 var service = {
   books: [
     { title: "Magician", author: "Raymond E. Feist" },
     { title: "The Hobbit", author: "J.R.R Tolkien" }
   ],

   addBook: function ( book ) {
     service.books.push( book );
     $rootScope.$broadcast( 'books.update' );
   }
 }

 return service;
}]);

CONTROLLERS

Controllers should be used purely to wire up services, dependencies and other objects, and assign them to the view via scope. They’re also an excellent choice when needing to handle complex business logic in your views.

var ctrl = [ '$scope', 'Book', function( scope, Book ) {
  scope.$on( 'books.update', function( event ) {
    scope.books = Book.books;
  });

  scope.books = Book.books;
}];

module.controller( "books.list", ctrl );

DIRECTIVES

Angular defines directives as chunks of code you use for DOM manipulation, but I feel it’s also great for interactions.

module.directive( "addBookButton", [ 'Book', function( Book ) {
  return {
    restrict: "A",
    link: function( scope, element, attrs ) {
      element.bind( "click", function() {
        Book.addBook( { title: "Star Wars", author: "George Lucas" } );
      });
    }
  }
}]);
<button add-book-button>Add book</button>

Source: http://kirkbushell.me/when-to-use-directives-controllers-or-services-in-angular/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment