Home Web Front-end JS Tutorial AngularJS uses UI Router to implement form wizard_AngularJS

AngularJS uses UI Router to implement form wizard_AngularJS

May 16, 2016 pm 03:16 PM

We have seen that this technology has been applied to many web pages. Things like shopping carts, registration forms, onboarding flows, and many multi-step forms make it easier for users to fill out forms online.

Here we will build it:

Using UI Router, which can embed states and display different views for each state, we can make multi-step forms quite easy.

To quickly understand how UI Router works, read our article: AngularJS uses UI-Router routing

Let’s get down to business and start creating our best form yet!

Create project

Creating a project has a template structure. It requires a layout file, a view file for each form, a format file, and a JavaScript file.

The following is the file list, create them first, and then fill in the content

- index.html
- form.html
- form-profile.html
- form-interests.html
- form-payment.html
- app.js
- style.css
Copy after login

Each form-____.html represents an html file in a hierarchical structure. These structures ultimately create our form structure.

Our layout/template file index.html

We start our project by creating a main file to introduce all the resources we need. Here we use the index.html file as the main file

Now, we load the resources we need (AngularJS, ngAnimate, Ui Router, and other scripts and stylesheets) and set up a ui-view to tell the UI Router where our view needs to be displayed. Here we use Bootstrap to quickly apply styles.

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <!-- CSS -->
  <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootswatch/3.1.1/darkly/bootstrap.min.css">
  <link rel="stylesheet" href="style.css">
  <!-- JS -->
  <!-- load angular, nganimate, and ui-router -->
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-animate.min.js"></script>
  <script src="app.js"></script>
</head>
<!-- apply our angular app -->
<body ng-app="formApp">
  <div class="container">
    <!-- views will be injected here -->
    <div ui-view></div>
  </div>
</body>
</html>
Copy after login

After completing the introduction of all files, let us enter app.js to start creating the Angular application and the most basic routing configuration. Notice how we applied the Angular App (formApp) to the body.

Create our Angular App app.js

Now let’s create the application and routes. In a large application, you would definitely want to distribute your Angular applications, routes, and controllers into their own modules, but for our simple use case, we will put them all into the happy family of app.js middle.

Now we have an application that has ngAnimate and ui.router injected. We also established corresponding routes. Notice how we define the url, view file (templateUrl) and controller for each view area.

The form will be our main view area. It also has a subview area form.profile separated by . This idea can be realized when the application state changes (Translator: it may be routing, queryString, etc.), the subview will be displayed in the main view area. (Translator: And it can only update the subview area changes and record the subview area status).

We will demonstrate this in the next section. Now we need to create views for the form and its subview areas.

Let’s start by creating a new form.html. This file will serve as a template for the rest of our form view files, just as index.html is used as the overall template for the entire project. All we have to do is include ui-view in this file so that the nested declarations know where to inject their views.

<!-- form.html -->
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
  <div id="form-container">
    <div class="page-header text-center">
      <h2>Let's Be Friends</h2>
      <!-- the links to our nested states using relative paths -->
      <!-- add the active class if the state matches our ui-sref -->
      <div id="status-buttons" class="text-center">
        <a ui-sref-active="active" ui-sref=".profile"><span>1</span> Profile</a>
        <a ui-sref-active="active" ui-sref=".interests"><span>2</span> Interests</a>
        <a ui-sref-active="active" ui-sref=".payment"><span>3</span> Payment</a>
      </div>
    </div>
    <!-- use ng-submit to catch the form submission and use our Angular function -->
    <form id="signup-form" ng-submit="processForm()">
      <!-- our nested state views will be injected here -->
      <div id="form-views" ui-view></div>
    </form>
  </div>
  <!-- show our formData as it is being typed -->
  <pre class="brush:php;toolbar:false">
    {{ formData }}
  
Copy after login

Notice how we use ui-view for the second time in the project. This is the great thing about UI Router: we can nest declarations and views. This gives us a lot of flexibility when developing applications. For the contents of the UI Router view, please see the official documentation.

Add state-based activation class

We want every status button to be displayed when they are activated. In order to achieve this effect, we will use ui-sref-active provided by UI Router. If ui-sref is consistent with the current state, the class we specify will be added.

To add validation to your own forms, see AngularJS Form Validation.

Now, you might be wondering what our form actually looks like. Let’s open a browser and take a look.

So far, we’re not getting everything exactly as we’d hoped, but it’s the start of a series of great things. Let's go ahead and add a little styling, and later we'll add some embedded views and comments.

Basic Stylingstyle.css

We will design our form-container and status-buttons to make our form look better.

/* style.css */
/* BASIC STYLINGS
============================================================================= */
body              { padding-top:20px; }
/* form styling */
#form-container        { background:#2f2f2f; margin-bottom:20px;
  border-radius:5px; }
#form-container .page-header  { background:#151515; margin:0; padding:30px; 
  border-top-left-radius:5px; border-top-right-radius:5px; }
/* numbered buttons */
#status-buttons         { }
#status-buttons a        { color:#FFF; display:inline-block; font-size:12px; margin-right:10px; text-align:center; text-transform:uppercase; }
#status-buttons a:hover     { text-decoration:none; }
/* we will style the span as the circled number */
#status-buttons span      { background:#080808; display:block; height:30px; margin:0 auto 10px; padding-top:5px; width:30px; 
  border-radius:50%; }
/* active buttons turn light green-blue*/
#status-buttons a.active span  { background:#00BC8C; }
Copy after login

现在我们的按钮更好看了并且更符合我们想要的了,接下来我们看下嵌套视图。

嵌套视图form-profile.html, form-interests.html, form-payment.html

这部分会比较简单。我们将定义不同的带有我们需要的输入框的视图。并且将他们绑定到formData对象以便我们能看到输入的数据。

下面是我们用于嵌套视图的视图文件:

表单概要视图

<!-- form-profile.html -->
<div class="form-group">
  <label for="name">Name</label>
  <input type="text" class="form-control" name="name" ng-model="formData.name">
</div>
<div class="form-group">
  <label for="email">Email</label>
  <input type="text" class="form-control" name="email" ng-model="formData.email">
</div>
<div class="form-group row">
<div class="col-xs-6 col-xs-offset-3">
  <a ui-sref="form.interests" class="btn btn-block btn-info">
  Next Section <span class="glyphicon glyphicon-circle-arrow-right"></span>
  </a>
</div>
</div>
Copy after login

表单兴趣视图

<!-- form-interests.html -->
<label>What's Your Console of Choice&#63;</label>
<div class="form-group">
  <div class="radio">
    <label>
      <input type="radio" ng-model="formData.type" value="xbox" checked>
      I like XBOX
    </label>
  </div>
  <div class="radio">
    <label>
      <input type="radio" ng-model="formData.type" value="ps">
      I like PS4
    </label>
  </div>
</div>
<div class="form-group row">
<div class="col-xs-6 col-xs-offset-3">
  <a ui-sref="form.payment" class="btn btn-block btn-info">
  Next Section <span class="glyphicon glyphicon-circle-arrow-right"></span>
  </a>
</div>
</div>
Copy after login

表单支付视图

<!-- form-payment.html -->
<div class="text-center">
  <span class="glyphicon glyphicon-heart"></span>
  <h3>Thanks For Your Money!</h3>
  <button type="submit" class="btn btn-danger">Submit</button>
</div>
Copy after login

既然我们已经定义了这些视图,那么当我们浏览表单时,他们就会显示出来。同样我们用下一个按钮和ui-sref来连接每一个新视图.

当使用ui-sref时,你要连接到你路由中定义的state而不是URL。然后Angular会使用这个来为你构建href。

下面是我们表单目前的每一个页面。

为了让我们的页面不同寻常,让我们加上动画效果。

让我们的表单产生动画效果

因为在项目开始的时候,我们已经加载了ngAnimate,它已经添加到需要动画的的类上了。当视图进入或退出的时候,它将自动添加类ng-enter和ng-leave。

现在我们所有做的就是通过样式形成我们最终的表单。为了理解Angular动画,这篇文章是一个很好的起点。

让我们进去css文件,将动画,并应用到我们的表单上

/* style.css */
/* ANIMATION STYLINGS
============================================================================= */
#signup-form      { position:relative; min-height:300px; overflow:hidden; padding:30px; }
#form-views       { width:auto; }
/* basic styling for entering and leaving */
/* left and right added to ensure full width */
#form-views.ng-enter,
#form-views.ng-leave   { position:absolute; left:30px; right:30px;
  transition:0.5s all ease; -moz-transition:0.5s all ease; -webkit-transition:0.5s all ease; 
}
/* enter animation */
#form-views.ng-enter      { 
  -webkit-animation:slideInRight 0.5s both ease;
  -moz-animation:slideInRight 0.5s both ease;
  animation:slideInRight 0.5s both ease; 
}
/* leave animation */
#form-views.ng-leave      { 
  -webkit-animation:slideOutLeft 0.5s both ease;
  -moz-animation:slideOutLeft 0.5s both ease;
  animation:slideOutLeft 0.5s both ease;  
}
/* ANIMATIONS
============================================================================= */
/* slide out to the left */
@keyframes slideOutLeft {
  to     { transform: translateX(-200%); }
}
@-moz-keyframes slideOutLeft {  
  to     { -moz-transform: translateX(-200%); }
}
@-webkit-keyframes slideOutLeft {
  to     { -webkit-transform: translateX(-200%); }
}
/* slide in from the right */
@keyframes slideInRight {
  from   { transform:translateX(200%); }
  to     { transform: translateX(0); }
}
@-moz-keyframes slideInRight {
  from   { -moz-transform:translateX(200%); }
  to     { -moz-transform: translateX(0); }
}
@-webkit-keyframes slideInRight {
  from   { -webkit-transform:translateX(200%); }
  to     { -webkit-transform: translateX(0); }
}
Copy after login

首先,确定视图离开或进去时,表单的样式,他们是绝对定位的。需要确认当视图进入的时候一个视图不会放到另一个视图的下面。

其次,应用我们的动画到.ng-enter和.ng-leave类

第三,用@keyframes定义动画。所有这些部分组合到一起,我们的表单就有了Angular动画,基于状态的UI Router和Angular数据绑定。

以上所述是小编给大家分享的AngularJS 使用 UI Router 实现表单向导的相关知识,希望对大家有所帮助。

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...

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.

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.

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...

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. �...

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.

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles