AngularJS: When should I use Directive, Controller, Service? "A must See for beginners"

Source: Internet
Author: User

(This article you must see, especially beginners, okay?) )

The translation of poor autumn in the desert

Angularjs is a very powerful front-end MVC framework. At the same time, it also introduces quite a few concepts that we may not be too familiar with. (Translator Note: Foreigner is really modest, my big celestial yards farming to these concepts that is quite familiar with Ah!) These concepts are:

    • Directive (instruction)
    • Controller (Controllers)
    • Service (services)

Let's look at these concepts one by one, study why they are as powerful as they were designed to be, and look at why we use them in that way. We start with the service.

Services (Service)

If you have already used Angularjs, you may have already met the concept of service, in short, the service is an alias of "Singleton" in Angluarjs. These little things (a single object) are often transmitted to ensure that every time you access the same instance, this is different from the factory model. Based on this idea, a singleton object allows us to implement some pretty cool features that allow many controllers and directive to access internal values. This is also one of the most common problems in the #angularjs channel (translator's note: The original author's own blog Channel), which is how to share data between different blocks of code in your app? Let's look at the problem.

We'll start by creating a module, and all the code in this article will use this module.

var module = angular.module( "my.new.module", [] );

Next, let's create a new service. Let's say that the module above is used to manage books. So, here we create a book service, and then add a JSON object array to this Serice, which represents a lot of book data.

 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;}]);

This is a very simple service (sometimes it's enough for you). What we're doing here is managing a book array with a Addbook method that can add more books when needed. The Addbook method also broadcasts an event on application that tells everyone who is using our service that the array has been updated so that they can do some flushing themselves. Now all we have to do is pass the service to a variety of controllers, Directive, filter, or anything else that needs it---and then they can access these methods and properties in the service. OK, let's do it.

 var ctrl = [ ‘$scope‘, ‘Book‘, function( scope, Book ) {   scope.$on( ‘books.update‘, function( event ) {     scope.books = Book.books;     scope.$apply();//注意,原文这里少了这一行   });    scope.books = Book.books; }]; module.controller( "books.list", ctrl );

Also very simple. What we have done above is to create a new controller for our module. The $scope Provdier and our own book service were passed to it at the time of creation. Can you understand what we're doing? We assign the books array in the book service created earlier to the local scope object inside the controller. It's cool, isn't it?

Okay, what's the core problem here? We saved some time and created an array on the controller. Yes,---we did. It certainly saves us a little bit of time---but what if we have to deal with the information elsewhere? Maintaining data through scope is a very rough way. Because of the influence of other controllers, directive, and model, scope can easily crash or become dirty. It will soon become a mess. Managing all of the book data through a centralized approach (here is the service), and then requesting a modification in some way, is not only clearer---but also easier to manage when the volume of the application grows. Finally, it can also keep your code modular (which is one thing angular is good at). Once you need to use this service in other projects, you don't need to go around the scope, controller, filter, and so on to find the relevant code, because everything is inside the service!

Good. So when should we use the service? The answer is: whenever we need to share data in different domains. In addition, thanks to angular's dependency injection system, it is easy and clear to achieve this.

CONTROLLERS (Controller)

Let's see the controller again! Unless you've used front-end MVC before, moving from a service-side MVC mindset to a client MVC mindset is like a brain teaser. Why is that? This is because, while the controller implements very similar functionality in front-end development, it also implements a number of features that are very different from the server controller. In angular, the controller itself does not handle "request" unless it is used to process routing (many people call this a route controller to create route controllers---), and more specifically, In particular, the controllers in your application that are part of the interface will only manage a very small piece of code.

Controllers should be purely used to concatenate service, dependencies, and other objects together, and then link them to the view through scope. If you need to deal with complex business logic in your view, it's also a good idea to put them in the controller. Back to the books example in front of us, I don't actually have anything to add to the controller.

But Kirk (note: Referring to the author of this article), what if I want to add a book? Should I add a new method to the controller to deal with this matter? No, the reason is explained below. Because it is part of the DOM interaction/operation. So please put it in the directive (instruction). How do you do it? I'm glad you can ask this question.

directives (instruction)

So far, in the large number of ANGULARJS applications we have written, the most significant and complex parts of the application are in Directive (directives). There is a powerful tool that can be used to manipulate and modify the DOM, which is what we need to discuss here. Let's provide a button that the user can use to add a book to the service to end the article with this feature.

A common anti-pattern (according to my humble opinion) is to add dom interaction code inside the controller. Angular's definition of directive is a piece of code that you can use to manipulate the DOM, but I think directive is also a good choice for user interaction. Let's extend the previous example by providing a button for the user to add a book to the service.

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" } );            });        }    }}]);

Very simple stuff. We have created a directive whose core purpose is simply to add a book to the books list, books is already registered in our books service. Let's apply this directive to our view.

<button add-book-button>Add book</button>

As you can see, we only use the instruction as an element attribute. Each time you click on this button, it will add star Wars (Star Wars) to our book Service. Simple, easy, modular---and easy to reuse. Well, why don't we just add a addbook to the controller, for example, like this:

 $scope.addBook = function() {     Book.addBook( { title: "Star Wars", author: "George Lucas" } ); };

So we can get the same result, right? Yes, that's true---but doing so poses a major problem. Once I need to add a book somewhere else, I have to copy this code (very un-dry!) (Translator Note: DRY---Dont Repeat yourself, seems to be an important coding principle advocated by Ruby. ), or refactoring (refactoring itself is not a bad thing). By building a directive directly, we don't have to worry about it later---it doesn't take any time to implement the same functionality again. By building instructions for DOM interaction and modification, we can immediately take the step to deal with the ever-increasing complexity of applications as business needs evolve. This is a pretty good thing, because it guarantees that we can fight less with our own implementations and can always write DRYer code.

Angular's modular reliance philosophy has undoubtedly made it an extraordinary framework. It gives us the ability to write our front-end code in such a way that we don't do it ourselves, and we don't flip the frame---it's probably the strongest force.

Hopefully I've explained exactly when and where you should use these angular concepts to better write your own code.

Original link:

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

Other related content:

1, "AngularJS" a book has been published by the electronics industry publishing house

http://damoqiongqiu.iteye.com/blog/1965167

2, "AngularJS" 5 examples of detailed directive (Directive) mechanism

http://damoqiongqiu.iteye.com/blog/1917971

3. Angularjs form Basis

http://damoqiongqiu.iteye.com/blog/1920191

4. AngularJS Form Advanced: remote check and custom input

http://damoqiongqiu.iteye.com/blog/1920993

5. AngularJS: Install Yeoman on Windows

http://damoqiongqiu.iteye.com/blog/1885371

6, contrast Angular/jqueryui/extjs: No one frame is omnipotent

http://damoqiongqiu.iteye.com/blog/1922004

7. Using Jstestdriver to implement JavaScript unit testing

http://damoqiongqiu.iteye.com/blog/1924415

8. JavaScript Unit Test series two: integrate Jasmine into jstestdriver

http://damoqiongqiu.iteye.com/blog/1925974

AngularJS: When should I use Directive, Controller, Service? "A must See for beginners"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.