Detailed analysis of the Form submission method in AngularJS programming, angularjs form

Source: Internet
Author: User
Tags php server php form php form processing

Detailed analysis of the Form submission method in AngularJS programming, angularjs form

Before AngularJS appeared, many developers faced the form submission problem. Because the form submission methods are complicated and different, it is easy to go crazy ...... However, it seems that it will still drive people crazy.

Today, we will take a look at the forms submitted using PHP in the past, and now how to convert them to submit using Angular. Using Angular to process forms is an "aha" moment for me (TRANSLATOR: A pleasure to understand or discover something ). Even though it doesn't even involve much Angular surface, it helps users see the potential of Form submission and understand the two data binding methods.

We will use the jQuery platform for this process. Therefore, you must first use javascript. We will submit a form to Display Error information, add error classes, and display and hide information in javascript.

Then Angular is used. Before using it, we need to do most of the necessary work, and much of the work we have done before will be very easy. Let's get started.

Simple Form

We will focus on two forms submission methods:

  • Old method: jQuery and PHP submit forms
  • New Method: submit forms in AngularJS and PHP

First, let's take a look at our form, which is super simple:

Form requirements

  • Implement new forms without refreshing pages
  • Enter name and superhero alias
  • If any error occurs, an error prompt is displayed.
  • If the input is incorrect, the input is red.
  • If all content is OK, a success prompt is displayed.

Document Structure

In our presentation, we only need two files.

  • Index.html
  • Process. php

Form Processing

Let's create a new PHP to process the form. This page is very small and uses the POST method to submit data.

Form Processing: This is not that important for us. You can use other languages you like to process your forms.

// process.php <?php $errors   = array();  // array to hold validation errors$data    = array();   // array to pass back data // validate the variables ====================================================== if (empty($_POST['name']))  $errors['name'] = 'Name is required.';  if (empty($_POST['superheroAlias']))  $errors['superheroAlias'] = 'Superhero alias is required.'; // return a response ===========================================================  // response if there are errors if ( ! empty($errors)) {   // if there are items in our errors array, return those errors  $data['success'] = false;  $data['errors'] = $errors; } else {   // if there are no errors, return a message  $data['success'] = true;  $data['message'] = 'Success!'; }  // return all our data to an AJAX call echo json_encode($data);
This is a very simple form processing script. We only check whether the data exists. If the data exists, no processing or operation is performed. If the data does not exist, we need to add a message to the $ errors array.

To return our data for AJAX calls, we need to use echo and json_encode. This is all the operations required for PHP form processing. This is also true when using jQuery AJAX or Angular to process forms.
Display form

Let's create an HTML to display our form

<!-- index.html --> <!doctype html>

Now we have a form. We also use Bootstrap to make the form look ugly. Using Bootstrap syntax rules, each input contains a spot to display the error message of our text.

Use jQuery to submit a form

Now, let's use jQuery to process form submission. I will add all the code to an empty <script> tag.

<!-- index.html --> ...  <!-- PROCESS FORM WITH AJAX (OLD) --> <script>  $(document).ready(function() {    // process the form   $('form').submit(function(event) {     // remove the past errors    $('#name-group').removeClass('has-error');    $('#name-group .help-block').empty();    $('#superhero-group').removeClass('has-error');    $('#superhero-group .help-block').empty();     // remove success messages    $('#messages').removeClass('alert alert-success').empty();     // get the form data    var formData = {     'name'     : $('input[name=name]').val(),     'superheroAlias'  : $('input[name=superheroAlias]').val()    };     // process the form    $.ajax({     type   : 'POST',     url   : 'process.php',     data   : formData,     dataType  : 'json',     success  : function(data) {       // log data to the console so we can see      console.log(data);       // if validation fails      // add the error class to show a red input      // add the error message to the help block under the input      if ( ! data.success) {        if ( {        $('#name-group').addClass('has-error');        $('#name-group .help-block').html(;       }        if (data.errors.superheroAlias) {        $('#superhero-group').addClass('has-error');        $('#superhero-group .help-block').html(data.errors.superheroAlias);       }       } else {        // if validation is good add success message       $('#messages').addClass('alert alert-success').append('<p>' + data.message + '</p>');      }     }    });     // stop the form from submitting and refreshing    event.preventDefault();   });   }); </script> ...

There is a lot of code to process the form here. We have the code to get the variables in the form, the code to send data to our form using AJAX, and the code to check whether there are errors and display successful prompts. In addition, we hope that the previous error information will be cleared after each form submission. It is indeed a lot of code.

If the form contains an error, then:

If the submission is successful:

Now, let's see that Angular is used to submit the same form. Remember, our applications still have the same features (displaying errors and success messages in the same place) without changing any content about how PHP processes forms ).

Use Angular to submit a form

We are going to set our Angular application in the previously used <script> tag. So we can start to delete the content.
Set an Angular Application


1. Load Angular

2. Set module

3. This is controller

4. Apply module and controller to HTML

5. Set bidirectional variable binding

6. This is an error and message.

It looks like a lot of content, but in the end, we will use a very small amount of code, and it looks very concise. In addition, it is easier to create a form with more input and greater input.

Angular components and controllers

First, load Angular and create components and controllers.

<!-- index.html --> ...  <!-- LOAD JQUERY --> <script src="//"></script> <!-- LOAD ANGULAR --> <script src="//"></script>  <!-- PROCESS FORM WITH AJAX (NEW) --> <script>   // define angular module/app  var formApp = angular.module('formApp', []);   // create angular controller and pass in $scope and $http  function formController($scope, $http) {   }  </script>

Now we have the foundation of Angular applications. We have loaded Angular, created component modules and controllers, and applied them to our website.

Next, I will show how two-way binding works.

Bidirectional data binding

This is one of Angular's core ideas and one of the most powerful features. In the Angular document, we can see that "Data Binding in Angular web applications is the automatic data synchronization between the model and the view layer ." This means that we need to capture data in the form. Using $ ('input [name = name] '). val () is not required.

In Angular, we bind data and variables together. For javascript or view, we can change both of them as long as there is a change.

To demonstrate data binding, we need to obtain the form input to automatically fill in the formData variable. Let's go back to the Angular Controller Applied to the page. Let's talk about $ scope and $ http.

$ Scope: adhesive between the Controller and the view layer. Basically, variables use $ scope to pass and communicate between our controller and the view layer. For detailed definitions, see the documentation.

$ Http: Angular service helps us process POST requests. For more information, see.

Use Data Binding to get Variables

Okay, let's talk less. We will apply these discussions to the form. The method is simpler than discussed above. We want to add one line to the Angular controller and view respectively.

<!-- index.html --> ...  <!-- PROCESS FORM WITH AJAX (NEW) --> <script>   // define angular module/app  var formApp = angular.module('formApp', []);   // create angular controller and pass in $scope and $http  function formController($scope, $http) {    // create a blank object to hold our form information   // $scope will allow this to pass between controller and view   $scope.formData = {};   } ...

Now, we have created a formData object. Let's fill it with form data. Before calling each input and obtaining val (), we use ng-model to bind a special input to the variable.

<!-- index.html --> ...  <!-- FORM --> <form>  <!-- NAME -->  <div id="name-group" class="form-group">   <label>Name</label>   <input type="text" name="name" class="form-control" placeholder="Bruce Wayne" ng-model="">   <span class="help-block"></span>  </div>   <!-- SUPERHERO NAME -->  <div id="superhero-group" class="form-group">   <label>Superhero Alias</label>   <input type="text" name="superheroAlias" class="form-control" placeholder="Caped Crusader" ng-model="formData.superheroAlias">   <span class="help-block"></span>  </div>   <!-- SUBMIT BUTTON -->  <button type="submit" class="btn btn-success btn-lg btn-block">   <span class="glyphicon glyphicon-flash"></span> Submit!  </button> </form>  <!-- SHOW DATA FROM INPUTS AS THEY ARE BEING TYPED --> <pre>  {{ formData }} </pre> ...

Now, Angular has bound each input to formData. When you enter each input box, you can see that the formData object is filled! Is it cool!

You do not have to use $ scope in the view. Everything is considered to be embedded in $ scope.
Process Form

In our old form, we use jQuery to submit the form, such as $ ('form'). submit (). Now we use the Angular feature called ng-submit. To complete this, we need to add a controller function to process the form, and then tell us that form uses this controller function:

<!-- index.html --> ...  <!-- PROCESS FORM WITH AJAX (NEW) --> <script>   // define angular module/app  var formApp = angular.module('formApp', []);   // create angular controller and pass in $scope and $http  function formController($scope, $http) {    // create a blank object to hold our form information   // $scope will allow this to pass between controller and view   $scope.formData = {};    // process the form   $scope.processForm = function() {    };   } ...  <!-- FORM --> <form ng-submit="processForm()"> ...

Now our form knows that the controller function is used for submission. Now that the form is in place, use $ http to process the form.

The syntax for processing the form looks like the original method. The advantage is that we do not need to manually capture form data, or inject, hide, and add a class to Display error or success information.

<!-- index.html --> ... // process the form$scope.processForm = function() { $http({  method : 'POST',  url  : 'process.php',  data : $.param($scope.formData), // pass in data as strings  headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload) })  .success(function(data) {   console.log(data);    if (!data.success) {    // if not successful, bind errors to error variables    $scope.errorName =;    $scope.errorSuperhero = data.errors.superheroAlias;   } else {    // if successful, bind success message to message    $scope.message = data.message;   }  });}; ...

This is our form! No class is added or removed. We need to clarify the error every time we submit the form. We only need to bind the variables and the view to be used. This is great because the processor is used to process data and the view is used to display data.

JQuery POST vs Angular POST

Sometimes we can see that data is not visible in the server when the POST method is submitted, because the serialization and sending methods of jQuery and Angular are different. This is due to your server language and its ability to understand the data submitted by Angular.

The above code is applied to the PHP server, and jQuery is required for the $. param function. Although many methods are not used to implement the content mentioned above, the only reason for using jQuery in this example is that it is simpler.

The following concise syntax will work based on your server language.

Concise syntax

In this example, data is sent as a string and your header information is sent. If you don't need this and want Angular $ http POST to be as concise as possible, you can use the shorthand method:

... $'process.php', $scope.formData)  .success(function(data) {   ...  });...

It is more concise and easier to remember.

$ Http Internal controller: Ideally, you can remove $ http requests from the controller to the service. This is only for demonstration purposes and will be discussed on the service as soon as possible.

Display errors and information in the view

We will use the ng-show and ng-class commands to process our views. Angular brackets allow us to place variables where we need them.

  • Ng-show: displays or hides elements based on the existence of variable values.
  • Ng-class: Adds or removes a class based on whether the variable value exists (or some other expressions ).
<!-- index.html --> ...  <!-- SHOW ERROR/SUCCESS MESSAGES --> <div id="messages" ng-show="message">{{ message }}</div>  <!-- FORM --> <form>  <!-- NAME -->  <div id="name-group" class="form-group" ng-class="{ 'has-error' : errorName }">   <label>Name</label>   <input type="text" name="name" class="form-control" placeholder="Bruce Wayne">   <span class="help-block" ng-show="errorName">{{ errorName }}</span>  </div>   <!-- SUPERHERO NAME -->  <div id="superhero-group" class="form-group" ng-class="{ 'has-error' : errorSuperhero }">   <label>Superhero Alias</label>   <input type="text" name="superheroAlias" class="form-control" placeholder="Caped Crusader">   <span class="help-block" ng-show="errorSuperhero">{{ errorSuperhero }}</span>  </div> ...

Our form is complete! With powerful Angular, we can remove these silly display/hidden js Code logic from the view. Now our js file is only used to process data, and the view can do its own thing.

The prompt information such as class and error/success will be displayed when it is available but hidden when it is not available. This is easier when we don't have to worry about whether we have considered it as comprehensively as using old javascript. You don't have to worry about hiding the error messages when each form is submitted.

For more information about Angular Form verification, see AngularJS Form Validation.

Now we have converted all beautiful forms into Angular. We have learned many concepts together and hope that you will have more contact with them and they will be easier to use.


  • Create an Angular module
  • Create an Angular controller
  • Bidirectional data binding
  • Bind ng-model to inputs
  • Ng-click Submit Form
  • An error occurred while displaying the form using bidirectional data binding.
  • Displays a div based on whether a variable exists.
  • Add a class based on whether the variable exists

These Angular technologies will be used in larger applications, and you can use them to create many good things. I wish Angular A pleasant journey. Please wait for more in-depth articles. At the same time, you can continue to learn Angular through in-depth understanding of its guides, services, and vendors.

Related Article

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