Home >Web Front-end >JS Tutorial >Tidy Up Your Angular Controllers with Factories and Services

Tidy Up Your Angular Controllers with Factories and Services

Jennifer Aniston
Jennifer AnistonOriginal
2025-02-21 12:28:10443browse

Tidy Up Your Angular Controllers with Factories and Services

About five or six years ago, jQuery dominated the web's clients. It reads like pure English, is easy to install, and has a smooth learning curve that even toddlers can easily get started. However, this ease of use also brings a series of problems. jQuery makes it easy to piece together something that is “usable”, but it comes at the expense of best practices, maintainability, and scalability. Then the framework war begins, and soon everyone scrambles to try the latest and best frameworks that promise to bring structure and scalability to their applications. AngularJS is one of the frameworks. Now, Angular's learning curve is much steeper than jQuery's, but I think it has evolved to the point where many developers can set up basic applications with fair confidence. In other words, using frameworks cannot automatically solve the core problems of application design. It is still possible to build non-maintainable or non-scalable applications in frameworks such as AngularJS, EmberJS, or React—in fact, it is quite common for beginners and even intermediate framework users to make this mistake.

Key Points

  • Use the Angular factory to encapsulate and manage object creation and configuration, separating the focus of object creation from the controller, thereby enhancing modularity and maintainability.
  • Implement services to handle data retrieval and business logic, streamlining the Angular controller so that it focuses only on view management.
  • Use the controllerAs syntax to simplify binding in templates and avoid common pitfalls related to using $scope, thereby enhancing the readability and maintainability of your code.
  • Refactor the controller by moving reusable logic to a service or factory, which helps maintain a clean and focused controller that primarily deals with view-related logic.
  • Test controllers, services and factories using frameworks such as Jasmine or Mocha to ensure components can operate independently and keep applications robust.
  • Abstract repetitive or shared features into services or factories to avoid code duplication and facilitate updating and managing features used in different parts of the application.

How is it so easy to get out of control?

To demonstrate how this sudden complexity occurs in even the most basic AngularJS application, let's start building an application and observe where we might go wrong. Then, we will look at the solution later.

Let's create a simple application

The application we are going to create is a Dribbble player scoring application. We will be able to enter the Dribbble user's name and add them to the scoreboard. Spoiler – You can see the effective implementation of the final product here. First create an index.html file containing the following content:

<code class="language-html"><!DOCTYPE html>

  
    <title>Angular 重构</title>
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
    
  
  
    <div class="container">
      <div class="panel panel-default">
        <div class="panel-heading">Dribbble 玩家分数</div>
        <div class="panel-body">
          <p>添加 Dribbble 玩家以查看他们的排名:</p>
          <div class="form-inline">
            <input class="form-control" type="text">
            <button class="btn btn-default">添加</button>
          </div>
        </div>
        <ul class="list-group"></ul>
      </div>
    </div>
  
</code>

Create our AngularJS application

If you have written Angular applications before, the next few steps should be very familiar. First, we will create an app.js file where we instantiate our AngularJS application:

<code class="language-html"><!DOCTYPE html>

  
    <title>Angular 重构</title>
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
    
  
  
    <div class="container">
      <div class="panel panel-default">
        <div class="panel-heading">Dribbble 玩家分数</div>
        <div class="panel-body">
          <p>添加 Dribbble 玩家以查看他们的排名:</p>
          <div class="form-inline">
            <input class="form-control" type="text">
            <button class="btn btn-default">添加</button>
          </div>
        </div>
        <ul class="list-group"></ul>
      </div>
    </div>
  
</code>

Now, we include it in our index.html file. We also add the ng-app="dribbbleScorer" attribute to our tag to bootstrap the Angular application.

<code class="language-javascript">var app = angular.module("dribbbleScorer", []);</code>

Now that our application is set up and booted, we can start processing the application's business logic.

(The following content is similar to the original text, but the sentences and vocabulary are adjusted to keep the original meaning unchanged, and some repeated steps are omitted to control the output length.)

By gradually adding functions (forms, Dribbble data acquisition, player removal, player use, player objects, and score calculation), the original text shows how to "run" the application step by step, but it also causes the controller code to become bloated and complex. .

Use Angular Factory to abstract our focus

The two concepts of adding and removing players are somewhat part of the controller. This is not so much that the controller exposes these functions, but rather that it is also responsible for their implementation. Wouldn't it be better if the controller's addPlayer() function just handed the request to another part of the application to handle the ins and outs of actually adding the player? This is where the AngularJS factory comes into play.

(The factory creation and use part in the original text has been rewritten, which is more concise and clear, and retains the core logic)

We created a DribbblePlayer factory, which is a constructor for creating Dribbble player objects. This factory is responsible for fetching data from the Dribbble API and adding it to the player object. By using this factory, we simplified the controller so that it is only responsible for adding and removing players.

(The improvements to factory functions in the original text, such as adding likeScore() and commentScore() methods, have also been similarly rewrited to make it more concise)

We also add the score calculation method to the DribbblePlayer factory as a method of player object. In this way, the controller code is more concise and only responsible for the logic related to the view.

Summary

This article demonstrates how to easily write “usable” code and how it quickly becomes difficult to maintain. We end up with a chaotic controller full of functions and responsibilities. However, after some refactoring, our controller file now looks like this:

<code class="language-html">
  ...
</code>

It's easier to read and focuses on very few things - that's what refactoring is about. I hope I've provided you with the necessary tools to get you started thinking about a better way to build AngularJS applications. Happy refactoring! The code for this tutorial is available on GitHub!

(The FAQ part at the end of the original text is omitted because the article is too long and has a weak relationship with the core content. If necessary, you can ask a separate FAQ question to answer.)

The above is the detailed content of Tidy Up Your Angular Controllers with Factories and Services. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn