search
HomeWeb Front-endJS TutorialHow to implement form wizard using AngularJS_AngularJS

Today we will create a multi-step form with animation using AngularJs and the great UI Router and the Angular ngAnimate module. This technique can be used on large forms where you want to simplify user operations.

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:

2015619120033761.jpg (1064×629)

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

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

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>

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.


// app.js
// create our angular app and inject ngAnimate and ui-router 
// =============================================================================
angular.module('formApp', ['ngAnimate', 'ui.router'])
 
// configuring our routes 
// =============================================================================
.config(function($stateProvider, $urlRouterProvider) {
   
  $stateProvider
   
    // route to show our basic form (/form)
    .state('form', {
      url: '/form',
      templateUrl: 'form.html',
      controller: 'formController'
    })
     
    // nested states 
    // each of these sections will have their own view
    // url will be nested (/form/profile)
    .state('form.profile', {
      url: '/profile',
      templateUrl: 'form-profile.html'
    })
     
    // url will be /form/interests
    .state('form.interests', {
      url: '/interests',
      templateUrl: 'form-interests.html'
    })
     
    // url will be /form/payment
    .state('form.payment', {
      url: '/payment',
      templateUrl: 'form-payment.html'
    });
     
  // catch all route
  // send users to the form page 
  $urlRouterProvider.otherwise('/form/profile');
})
 
// our controller for the form
// =============================================================================
.controller('formController', function($scope) {
   
  // we will store all of our form data in this object
  $scope.formData = {};
   
  // function to process the form
  $scope.processForm = function() {
    alert('awesome!');
  };
   
});

Now we have an application with 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.
Form template view form.html

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 id="Let-s-Be-Friends">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 }}
  

注意我们是如何第二次在项目中使用ui-view的。这就是UI Router伟大的地方:我们可以嵌套声明和视图。这能够在我们开发应用时提供给我们非常多的灵活性。关于UI Router视图的内容,请参见官方文档

添加基于状态的激活类

我们希望每一个状态按钮能够在他们被激活时展示。为了达到这个效果,我们将会使用UI Router提供的ui-sref-active。如果ui-sref和当前状态一致,则会添加我们指定的类。

现在,你可能想知道我们的表单究竟看起来是什么样子。让我们打开浏览器看一眼。

2015619120108560.png (613×307)

 目前为止,我们并没有完全按照希望的那样得到所有的内容,但是这是一系列伟大事情的开端。让我们继续前进,添加一点样式,之后会添加一些嵌入视图和注释。

基础Stylingstyle.css

我们将设计我们的form-container和status-buttons来是我们的表单看起来更好。
 

/* 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; }

现在我们的按钮更好看了并且更符合我们想要的了,接下来我们看下嵌套视图。
嵌套视图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>

表单兴趣视图
 

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

表单支付视图
 

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

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


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

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

2015619120129718.jpg (450×525)

2015619120150291.jpg (450×525)

2015619120206904.jpg (450×525)

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

因为在项目开始的时候,我们已经加载了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); }
}

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

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

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

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
PHP表单处理:表单数据查询与筛选PHP表单处理:表单数据查询与筛选Aug 07, 2023 pm 06:17 PM

PHP表单处理:表单数据查询与筛选引言在Web开发中,表单是一种重要的交互方式,用户可以通过表单向服务器提交数据并进行进一步的处理。本文将介绍如何使用PHP处理表单数据的查询与筛选功能。表单的设计与提交首先,我们需要设计一个包含查询与筛选功能的表单。常见的表单元素包括输入框、下拉列表、单选框、复选框等,根据具体需求进行设计。用户在提交表单时,会将数据以POS

2022年最新5款的angularjs教程从入门到精通2022年最新5款的angularjs教程从入门到精通Jun 15, 2017 pm 05:50 PM

Javascript 是一个非常有个性的语言. 无论是从代码的组织, 还是代码的编程范式, 还是面向对象理论都独具一格. 而很早就在争论的Javascript 是不是面向对象语言这个问题, 显然已有答案. 但是, 即使 Javascript 叱咤风云二十年, 如果想要看懂 jQuery, Angularjs, 甚至是 React 等流行框架, 观看《黑马云课堂JavaScript 高级框架设计视频教程》就对了。

Java实现表单的实时验证与提示功能Java实现表单的实时验证与提示功能Aug 07, 2023 am 10:42 AM

Java实现表单的实时验证与提示功能随着网络应用的普及和发展,表单的使用也变得越来越重要。表单是网页中用于收集和提交用户数据的元素,例如注册或登录页面的表单。在用户填写表单时,经常需要对其输入的数据进行验证和提示,以保证数据的正确性和完整性。在本文中,我们将介绍如何使用Java语言实现表单的实时验证与提示功能。HTML表单的搭建首先,我们需要使用HTML语言

如何在Nette框架中使用表单和验证?如何在Nette框架中使用表单和验证?Jun 04, 2023 pm 03:51 PM

Nette框架是一款用于PHPWeb开发的轻量级框架,以其简单易用、高效稳定的特点受到了广泛的欢迎和使用。在开发Web应用时,使用表单和验证是不可避免的需求。本文将介绍如何在Nette框架中使用表单和验证。一、表单构建在Nette框架中,表单可以通过Form类来创建。Form类在NetteForms命名空间中,可以通过use关键字引入。useNetteF

如何在PHP表单中增加Token验证机制如何在PHP表单中增加Token验证机制Jun 24, 2023 pm 04:54 PM

在Web开发中,表单是用户和服务器之间沟通的重要渠道。为确保安全,我们需要在表单提交时添加Token验证机制来避免恶意攻击者的进攻。Token验证的基本原理是:服务器生成随机数,在表单中添加隐藏域的方式将Token传递给客户端,客户端提交表单时将Token发送回服务器,服务器验证Token的正确性,如果匹配,则允许表单提交,否则拒绝提交。下面我们将介绍在PH

使用PHP和AngularJS搭建一个响应式网站,提供优质的用户体验使用PHP和AngularJS搭建一个响应式网站,提供优质的用户体验Jun 27, 2023 pm 07:37 PM

在如今信息时代,网站已经成为人们获取信息和交流的重要工具。一个响应式的网站能够适应各种设备,为用户提供优质的体验,成为了现代网站开发的热点。本篇文章将介绍如何使用PHP和AngularJS搭建一个响应式网站,从而提供优质的用户体验。PHP介绍PHP是一种开源的服务器端编程语言,非常适用于Web开发。PHP具有很多优点,如易于学习、跨平台、丰富的工具库、开发效

使用PHP和AngularJS构建Web应用使用PHP和AngularJS构建Web应用May 27, 2023 pm 08:10 PM

随着互联网的不断发展,Web应用已成为企业信息化建设的重要组成部分,也是现代化工作的必要手段。为了使Web应用能够便于开发、维护和扩展,开发人员需要选择适合自己开发需求的技术框架和编程语言。PHP和AngularJS是两种非常流行的Web开发技术,它们分别是服务器端和客户端的解决方案,通过结合使用可以大大提高Web应用的开发效率和使用体验。PHP的优势PHP

如何优化Vue开发中的表单自动填充问题如何优化Vue开发中的表单自动填充问题Jun 29, 2023 am 10:20 AM

如何优化Vue开发中的表单自动填充问题随着Vue框架的不断发展和应用,越来越多的开发者选择使用Vue来开发前端应用。在Vue开发过程中,表单是一个非常常见的组件,而表单自动填充问题也是开发者经常会遇到的一个问题。本文将介绍如何优化Vue开发中的表单自动填充问题,以提高用户体验。表单自动填充问题指的是当用户在表单中输入某些信息后,关闭浏览器再重新打开时,浏览器

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.