Home >Web Front-end >JS Tutorial >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
controllerAs
syntax to simplify binding in templates and avoid common pitfalls related to using $scope
, thereby enhancing the readability and maintainability of your code. 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!