Home Web Front-end JS Tutorial About the analysis of AngularJs Forms

About the analysis of AngularJs Forms

Jun 25, 2018 am 11:39 AM
angularjs

This article mainly introduces AngularJs Forms. Here we have compiled relevant information and simple sample codes. Friends in need can refer to it

Controls (input, select, textarea) are a way for users to input data. A Form is a collection of these controls designed to group related controls.

Forms and controls provide validation services, so users can receive prompts for invalid input. This provides a better user experience because users can get immediate feedback and know how to correct errors. Keep in mind that while client-side validation plays an important role in providing a good user experience, it can be easily bypassed and, therefore, cannot be trusted. Server-side authentication is still necessary for a secure application.

1. Simple form

The key directive to understand two-way data binding is ngModel. ngModel provides two-way data binding from model to view and view to model. Moreover, it also provides APIs to other directives to enhance their behavior.

<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="SimpleForm">
<head>
  <meta charset="UTF-8">
  <title>PropertyEvaluation</title>
  <style type="text/css">
    .ng-cloak {
      display: none;
    }
  </style>
</head>
<body>
<p ng-controller="MyCtrl" class="ng-cloak">
  <form novalidate>
    名字: <input ng-model="user.name" type="text"><br/>
    Email: <input ng-model="user.email" type="email"><br/>
    性别: <input value="男" ng-model="user.gender" type="radio">男
    <input value="女" ng-model="user.gender" type="radio">女
    <br/>
    <button ng-click="reset()">还原上次保存</button>
    <button ng-click="update(user)">保存</button>
  </form>
  <pre class="brush:php;toolbar:false">form = {{user | json}}
saved = {{saved | json}}

Copy after login

2. Using CSS classes

In order to make the form, control, and ngModel rich Style, you can add the following class:

  1. ng-valid

  2. ng-invalid

  3. ng -pristine (never entered)

  4. ng-dirty (entered)

The following example uses CSS to display Validity of each form control. In the example, user.name and user.email are both required, but when they are modified (dirty), the background will appear red. This ensures that the user is not distracted by an error until after interacting with the form (after submission?) and discovering that its validity was not met.

<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="CSSClasses">
<head>
  <meta charset="UTF-8">
  <title>CSSClasses</title>
  <style type="text/css">
    .ng-cloak {
      display: none;
    }
    .css-form input.ng-invalid.ng-dirty {
      background-color: #fa787e;
    }
    .css-form input.ng-valid.ng-dirty {
      background-color: #78fa89;
    }
  </style>
</head>
<body>
<p ng-controller="MyCtrl" class="ng-cloak">
  <form novalidate class="css-form" name="formName">
    名字: <input ng-model="user.name" type="text" required><br/>
    Email: <input ng-model="user.email" type="email" required><br/>
    性别: <input value="男" ng-model="user.gender" type="radio">男
    <input value="女" ng-model="user.gender" type="radio">女
    <br/>
    <button ng-click="reset()">RESET</button>
    <button ng-click="update(user)">SAVE</button>
  </form>
  <pre class="brush:php;toolbar:false">form = {{user | json}}
saved = {{saved | json}}

Copy after login

3. Binding to form and control state

In angular, the form is FormController An instance. The form instance can be exposed to the scope at will using the name attribute (I don't understand here, there is no property in the scope that is the same as the name attribute of the form, but because of the "document.form name" method, it can still be obtained ). Similarly, controls are instances of NgModelController. Control instances can similarly be exposed to forms using the name attribute. This shows that the internal properties of both the form and the control (control) are feasible for binding in the view using standard binding primitives.

This allows us to extend the above example with the following feature:

  1. The RESET button is only available after the form has changed.

  2. The SAVE button is only available when the form changes and the input is valid.

  3. Customize error messages for user.email and user.agree.

<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="ControlState">
<head>
  <meta charset="UTF-8">
  <title>ControlState</title>
  <style type="text/css">
    .ng-cloak {
      display: none;
    }
    .css-form input.ng-invalid.ng-dirty {
      background-color: #fa787e;
    }
    .css-form input.ng-valid.ng-dirty {
      background-color: #78fa89;
    }
  </style>
</head>
<body>
<p ng-controller="MyCtrl" class="ng-cloak">
  <form novalidate class="css-form" name="formName">
    名字: <input ng-model="user.name" name="userName" type="text" required><br/>
    <p ng-show="formName.userName.$dirty&&formName.userName.$invalid">
      <span>请填写名字</span>
    </p>
    Email: <input ng-model="user.email" name="userEmail" type="email" required><br/>
    <p ng-show="formName.userEmail.$dirty && formName.userEmail.$invalid">提示:
      <span ng-show="formName.userEmail.$error.required">请填写Email</span>
      <span ng-show="formName.userEmail.$error.email">这不是一个有效的Email</span>
    </p>
    性别: <input value="男" ng-model="user.gender" type="radio">男
    <input value="女" ng-model="user.gender" type="radio">女
    <br/>
    <input type="checkbox" ng-model="user.agree" name="userAgree" required/>我同意:
    <input type="text" ng-show="user.agree" ng-model="user.agreeSign" required/>
    <br/>
    <p ng-show="!formName.userAgree || !user.agreeSign">请同意并签名~</p>
    <button ng-click="reset()" ng-disabled="isUnchanged(user)">RESET</button>
    <button ng-click="update(user)" ng-disabled="formName.$invalid || isUnchanged(user)">SAVE</button>
  </form>
  <pre class="brush:php;toolbar:false">form = {{user | json}}
saved = {{saved | json}}

Copy after login

4. Custom Validation

Angular is most common HTML form field (input, text, number, url, email, radio, checkbox) types provide implementations, and there are also some directives (required, pattern,, inlength, maxlength, min, max) for form validation.

We can define our own validation plug-in by defining a directive that adds a custom validation function to the ngModel controller (is this a connected ngModelController?). To get a controller, the directive specifies dependencies as shown in the following example (require attribute in the directive definition object).

Model to View update - Whenever the Model changes, all functions in the ngModelController.$formatters (data validation and format conversion are triggered when the model changes) array will be queued for execution, so in Each function here has the opportunity to format the value of the model and pass NgModelController.$setValidity (http://code.angularjs.org/1.0.2/docs/api/ng.directive:ngModel.NgModelController#$setValidity ) to modify the validation status of the control.

View to Model update - A similar approach, whenever the user interacts with a control, NgModelController.$setViewValue will be triggered. At this time, it is the turn to execute NgModelController$parsers (after the control obtains the value from the DOM, it will execute all methods in this array, review, filter or convert the value, and also verify) all methods in the array.

In the following example we will create two directives.

The first one is integer, which is responsible for verifying whether the input is a valid integer. For example, 1.23 is an illegal value because it contains a decimal part. Note that we insert (unshift) at the head of the array instead of inserting (push) at the tail. This is because we want it to execute first and use the value of this control (it is estimated that this Array is used as a queue). We need to The validation function is executed before the conversion occurs.

第二个directive是smart-float。他将”1.2”和”1,2”转换为一个合法的浮点数”1.2”。注意,我们在这不可以使用HTML5的input类型”number”,因为浏览器不允许用户输入我们预期的非法字符,如”1,2”(它只认识”1.2”)。

<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="CustomValidation">
<head>
  <meta charset="UTF-8">
  <title>CustomValidation</title>
  <style type="text/css">
    .ng-cloak {
      display: none;
    }
    .css-form input.ng-invalid.ng-dirty {
      background-color: #fa787e;
    }
    .css-form input.ng-valid.ng-dirty {
      background-color: #78fa89;
    }
  </style>
</head>
<body>
<p class="ng-cloak">
  <form novalidate class="css-form" name="formName">
    <p>
      大小(整数 0 - 10):<input integer type="number" ng-model="size" name="size" min="0" max="10"/>{{size}}<br/>
      <span ng-show="formName.size.$error.integer">这不是一个有效的整数</span>
      <span ng-show="formName.size.$error.min || formName.size.$error.max">
        数值必须在0到10之间
      </span>
    </p>
    <p>
      长度(浮点数):
      <input type="text" ng-model="length" name="length" smart-float/>
      {{length}}<br/>
      <span ng-show="formName.length.0error.float">这不是一个有效的浮点数</span>
    </p>
  </form>
</p>
<script src="../angular-1.0.1.js" type="text/javascript"></script>
<script type="text/javascript">
  var app = angular.module("CustomValidation", []);
  var INTEGER_REGEXP = /^\-?\d*$/;
  app.directive("integer", function () {
    return {
      require:"ngModel",//NgModelController
      link:function(scope,ele,attrs,ctrl) {
        ctrl.$parsers.unshift(function (viewValue) {//$parsers,View到Model的更新
          if(INTEGER_REGEXP.test(viewValue)) {
            //合格放心肉
            ctrl.$setValidity("integer", true);
            return viewValue;
          }else {
            //私宰肉……
            ctrl.$setValidity("integer", false);
            return undefined;
          }
        });
      }
    };
  });
  var FLOAT_REGEXP = /^\-?\d+(?:[.,]\d+)?$/;
  app.directive("smartFloat", function () {
    return {
      require:"ngModel",
      link:function(scope,ele,attrs,ctrl) {
        ctrl.$parsers.unshift(function(viewValue) {
          if(FLOAT_REGEXP.test(viewValue)) {
            ctrl.$setValidity("float", true);
            return parseFloat(viewValue.replace(",", "."));
          }else {
            ctrl.$setValidity("float", false);
            return undefined;
          }
        });
      }
    }
  });
</script>
</body>
</html>
Copy after login

五、Implementing custom form control (using ngModel)

  angular实现了所有HTML的基础控件(input,select,textarea),能胜任大多数场景。然而,如果我们需要更加灵活,我们可以通过编写一个directive来实现自定义表单控件的目的。

  为了制定控件和ngModel一起工作,并且实现双向数据绑定,它需要:

实现render方法,是负责在执行完并通过所有NgModelController.$formatters方法后,呈现数据的方法。

调用$setViewValue方法,无论任何时候用户与控件发生交互,model需要进行响应的更新。这通常在DOM事件监听器里实现。
  可以查看$compileProvider.directive获取更多信息。

  下面的例子展示如何添加双向数据绑定特性到可以编辑的元素中。

<!DOCTYPE HTML>
<html lang="zh-cn" ng-app="CustomControl">
<head>
  <meta charset="UTF-8">
  <title>CustomControl</title>
  <style type="text/css">
    .ng-cloak {
      display: none;
    }
    p[contenteditable] {
      cursor: pointer;
      background-color: #D0D0D0;
    }
  </style>
</head>
<body ng-controller="MyCtrl">
<p class="ng-cloak">
  <p contenteditable="true" ng-model="content" title="点击后编辑">My Little Dada</p>
  <pre class="brush:php;toolbar:false">model = {{content}}

Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于Angular4 中内置指令的基本用法

在angularJs中如何实现清除浏览器缓存

在Angular2中有关自定义管道格式数据用法

The above is the detailed content of About the analysis of AngularJs Forms. 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)

The latest 5 angularjs tutorials in 2022, from entry to mastery The latest 5 angularjs tutorials in 2022, from entry to mastery Jun 15, 2017 pm 05:50 PM

Javascript is a very unique language. It is unique in terms of the organization of the code, the programming paradigm of the code, and the object-oriented theory. The issue of whether Javascript is an object-oriented language that has been debated for a long time has obviously been There is an answer. However, even though Javascript has been dominant for twenty years, if you want to understand popular frameworks such as jQuery, Angularjs, and even React, just watch the "Black Horse Cloud Classroom JavaScript Advanced Framework Design Video Tutorial".

Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Use PHP and AngularJS to build a responsive website to provide a high-quality user experience Jun 27, 2023 pm 07:37 PM

In today's information age, websites have become an important tool for people to obtain information and communicate. A responsive website can adapt to various devices and provide users with a high-quality experience, which has become a hot spot in modern website development. This article will introduce how to use PHP and AngularJS to build a responsive website to provide a high-quality user experience. Introduction to PHP PHP is an open source server-side programming language ideal for web development. PHP has many advantages, such as easy to learn, cross-platform, rich tool library, development efficiency

Build web applications using PHP and AngularJS Build web applications using PHP and AngularJS May 27, 2023 pm 08:10 PM

With the continuous development of the Internet, Web applications have become an important part of enterprise information construction and a necessary means of modernization work. In order to make web applications easy to develop, maintain and expand, developers need to choose a technical framework and programming language that suits their development needs. PHP and AngularJS are two very popular web development technologies. They are server-side and client-side solutions respectively. Their combined use can greatly improve the development efficiency and user experience of web applications. Advantages of PHPPHP

Build a single-page web application using Flask and AngularJS Build a single-page web application using Flask and AngularJS Jun 17, 2023 am 08:49 AM

With the rapid development of Web technology, Single Page Web Application (SinglePage Application, SPA) has become an increasingly popular Web application model. Compared with traditional multi-page web applications, the biggest advantage of SPA is that the user experience is smoother, and the computing pressure on the server is also greatly reduced. In this article, we will introduce how to build a simple SPA using Flask and AngularJS. Flask is a lightweight Py

Introduction to the basics of AngularJS Introduction to the basics of AngularJS Apr 21, 2018 am 10:37 AM

The content of this article is about the basic introduction to AngularJS. It has certain reference value. Now I share it with you. Friends in need can refer to it.

How to use AngularJS in PHP programming? How to use AngularJS in PHP programming? Jun 12, 2023 am 09:40 AM

With the popularity of web applications, the front-end framework AngularJS has become increasingly popular. AngularJS is a JavaScript framework developed by Google that helps you build web applications with dynamic web application capabilities. On the other hand, for backend programming, PHP is a very popular programming language. If you are using PHP for server-side programming, then using PHP with AngularJS will bring more dynamic effects to your website.

Use PHP and AngularJS to develop an online file management platform to facilitate file management Use PHP and AngularJS to develop an online file management platform to facilitate file management Jun 27, 2023 pm 01:34 PM

With the popularity of the Internet, more and more people are using the network to transfer and share files. However, due to various reasons, using traditional methods such as FTP for file management cannot meet the needs of modern users. Therefore, establishing an easy-to-use, efficient, and secure online file management platform has become a trend. The online file management platform introduced in this article is based on PHP and AngularJS. It can easily perform file upload, download, edit, delete and other operations, and provides a series of powerful functions, such as file sharing, search,

How to use PHP and AngularJS for front-end development How to use PHP and AngularJS for front-end development May 11, 2023 pm 05:18 PM

With the popularity and development of the Internet, front-end development has become more and more important. As front-end developers, we need to understand and master various development tools and technologies. Among them, PHP and AngularJS are two very useful and popular tools. In this article, we will explain how to use these two tools for front-end development. 1. Introduction to PHP PHP is a popular open source server-side scripting language. It is suitable for web development and can run on web servers and various operating systems. The advantages of PHP are simplicity, speed and convenience

See all articles