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

Tidy Up Your Angular Controllers with Factories and Services

Feb 21, 2025 pm 12:28 PM

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:

<!DOCTYPE html>
<html>
  <head>
    <title>Angular 重构</title>
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
    <🎜>
  </head>
  <body>
    <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>
  </body>
</html>
Copy after login
Copy after login

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:

<!DOCTYPE html>
<html>
  <head>
    <title>Angular 重构</title>
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
    <🎜>
  </head>
  <body>
    <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>
  </body>
</html>
Copy after login
Copy after login

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

var app = angular.module("dribbbleScorer", []);
Copy after login

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:

<html ng-app="dribbbleScorer">
  ...
</html>
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles