Home  >  Article  >  Web Front-end  >  About the analysis of AngularJs Forms

About the analysis of AngularJs Forms

不言
不言Original
2018-06-25 11:39:132339browse

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

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

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

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>

五、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}}

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注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:
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