Angularjs Development Guide 6:angularjs form detailed

Source: Internet
Author: User

The form control (input, select, textarea) is used to get user input. A form is a set of linked form controls.

Users can provide validated services through forms and form controls, knowing that their input is legitimate. This allows user interaction to be friendly, as users can correct their errors with feedback. However, although client-side validation can play a significant role, it is also easy to bypass, so it is not entirely dependent on client-side validation. To build secure applications, server-side validation is essential.

The key to understanding ANGULARJS bidirectional binding is to understand the ngModel instructions. This instruction enables two-way binding by dynamically mapping the model and view to each other.

In order to beautify the form and form elements, the Ngmodel directive automatically adds the following CSS classes to the element:

    • Ng-valid
    • Ng-invalid
    • Ng-pristine
    • Ng-dirty

A form is an instance where a FormController form instance can be selectively exposed to the scope through the Name property. Similarly, a form control is also an NgModelController instance, and form controls can be exposed to the scope as well. This means that the view can get the state of the form or form control through the basic functionality of the binding.

    • The reset button is displayed only when the form changes.
    • The Save button is displayed only if the form has changed and the value changed is legal.
    • Can customize error messages for User.email and User.agree.

As an example:

<!doctype html>functionController ($scope) {$scope. master= {}; $scope. Update=function(user) {$scope. master=angular.copy (user);        }; $scope. Reset=function() {$scope. User=angular.copy ($scope. master);        }; $scope. isunchanged=function(user) {returnangular.equals (user, $scope. master);        };    $scope. Reset (); }    </script> Name:<input type= "text" ng-model= "User.Name" name= "uName" required/><br/>//required, this input box must have contentE-Mail:<input type= "Email" ng-model= "User.email" name= "Uemail" required/><br/> <div ng-show= "form.uEmail.$ Dirty && form.uemail. $invalid ">Invalid://This div is displayed if the contents of the INPUT element with name Uemail in the form table are illegal or dirty data. <span ng-show= "Form.uemail. $error. Required" >tell us your email.</span>//If the error message is caused by required, this span is displayed <span ng-show= "Form.uemail. $error. Email" >this is not a valid email.</span>//If the error message is caused by an illegal content inside, this s Pan </div>Gender:<input type= "Radio" ng-model= "User.gender" value= "male"/>male <input type= "Radio" ng-model= "User.gender" Value= "female"/>female<br/> <input type= "checkbox" ng-model= "User.agree" name= "Useragree" required/&        Gt I agree: <input ng-show= "User.agree" type= "text" ng-model= "User.agreesign"Required/><br/> <div ng-show= "!user.agree | | !user.agreesign ">please agree and sign.</div> <button ng-click=" reset () "ng-disabled=" isunchanged (user) ">RESET</button> <button ng-click=" Update (user)ng-disabled= "form. $invalid | | isunchanged (user) ">SAVE</button>//If the entire form form is not validated or the contents of the form form are not changed, this button is not clickable </form> </div&gt  ; </body>

ANGULARJS implements most common HTML5 form input elements (text, number, URL, email, radio, checkbox), and also implements many instructions for validation (required, pattern, minlength, MaxLength, Min, max).

If you want to define your own authenticator, you can do this by adding a validation function to the Ngmodel controller in your own instructions. To obtain a reference to a controller, you need to specify a dependency in the instruction, and the validation function can be written in two places.

    • Model-to-view updates-as long as the bound model changes, ngmodelcontroller# $formatters the functions in the array are called in turn, so each function has the opportunity to format the data, and of course you can ngmodelcontroller# $setValidity to change the validation status of the form.

    • View to the update of the model-the same as long as the user interacts with the form, the ngmodelcontroller# $setViewValue is called. This is ngmodelcontroller# $parsers the functions in the array are called sequentially, each function has the opportunity to change the value or to change the validation state of the form by ngmodelcontroller# $setValidity. In the following example, this is used.

As an example:

<!doctype html>varApp = Angular.module (' Form-example1 ', []); varInteger_regexp =/^\-?\d+$/; Either start with a "-" (negative), or no minus sign, followed by a positive integer, including 0 app.directive (' Integer ',function() {return{require:' Ngmodel ',//dependent nogmodel Directive Link:function(Scope, Elm, Attrs, ctrl) {CTRL. $parsers. Unshift (function(viewvalue) {//ctrl can invoke the method defined in the controller function in the Ngmodel Directiveif(Integer_regexp.test (Viewvalue)) {Ctrl. $setValidity (' Integer ',true); returnViewvalue; } Else {Ctrl. $setValidity (' Integer ',false); returnundefined;            }           });      }        };      }); varFloat_regexp =/^\-?\d+ ((\.| \,) \d+)? $/; can be positive or negative, can be an integer, or it can be a floating-point number, floating-point numbers can be used "."      Separate, can also use "," separate. App.directive (' Smartfloat ',function() {return{require:' Ngmodel ', Link:function(Scope, Elm, Attrs, ctrl) {CTRL. $parsers. Unshift (function(viewvalue) {if(Float_regexp.test (Viewvalue)) {Ctrl. $setValidity (' Float ',true); returnParsefloat (Viewvalue.replace (', ', '. '))); } Else{Ctrl. $setValidity (' Float ',false); returnundefined;            }           });      }        };    }); </script> Size (integer0-10):          <input type= "number" ng-model= "size" name= "size"min= "0" max= "ten" integer/>{{size}}<br/>//integer, custom Directive <span ng-show= "form.size. $error. Integer" > This is not valid integer!</span> <span ng-show= "form.size. $error. Min | | Form.size. $error. Max ">The value must beinchRange 0 to 10!</span> </div> <div>Length (float):          <input type= "text" ng-model= "Length" name= "Length" smart-float/>{{length}}<br/>//smart-float, custom directives
          <span ng-show= "form.length. $error. Float" >float number!</span>        </div>      </form>    </div>  </body>

In the example above, we have created two instructions.

    • The first instruction is to verify that the input is an integer. For example, 1.23 does not conform to the validated value because it contains fractional parts.

    • The second instruction is to verify that the input is "smart floating point (Smart-float)". It can convert "1.2" or "all" to a valid floating-point number "1.2". Note that we cannot use the type= "number" of the input element here, because browsers that support HTML5 do not allow users to enter illegal values such as "up".

ANGULARJS has implemented all the basic HTML form controls (Input,select,textarea), which should suffice for most cases. However, you can still implement your own form control by writing instructions.

To work with the Ngmodel directive to implement a custom control, and to implement two-way binding, you need:

    • Implement the Render method. This method is responsible for rendering the new data on the view when the data model changes, passing the changed value to the ngmodelcontroller# $formatters.
    • The $setviewvalue method is called when the user interacts with the control and the model needs to be updated. This is usually done in the DOM's listener event.

The following example shows how to add a "content-editable" data-bound element.

<!doctype html>Angular.module (' Form-example2 ', []). directive (' contenteditable ',function() {//custom directive contenteditablereturn{require:' Ngmodel ', Link:function(Scope, Elm, Attrs, ctrl) {//View -and modelElm.bind (' Blur ',function() {//to the element div bound Blur event scope. $apply (function() {Ctrl. $setViewValue (Elm.html ());                 Update Model} When the input is finished and the focus leaves the div element);                }); //Model --ViewCtrl. $render =function(value) {elm.html (value);                Update views View}; //load init value from DOMCtrl. $setViewValue (Elm.html ());    }       };    }); </script> div[contenteditable] {cursor:pointer; Background-color: #D0D0D0; }    </style> </body>

Come on!

Angularjs Development Guide 6:angularjs form detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.