English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed Explanation of AngularJS Form Submission Example

This article describes the form submission of AngularJS. Shared for everyone's reference, as follows:

Data binding in AngularJS

AngularJS creates real-time templates to replace the view instead of merging data into the template and then updating the DOM. Any value in an independent view component is dynamically replaced.

ng-The app attribute declares that all content contained within it belongs to this AngularJS application, which is why we can nest AngularJS applications within web applications. Only the content with ng-Only the DOM elements contained in the app attribute are affected by AngularJS.

When AngularJS considers that a value may change, it will run its own event loop to check whether this value has become 'dirty'. If the value has changed since the last event loop run, then this value is considered to be 'dirty'. This is also the way Angular can track and respond to changes in the application.

This process is called dirty checking. Dirty checking is an effective means to check changes in the data model. When potential changes exist, AngularJS will perform dirty checking during the event loop to ensure data consistency.

With AngularJS, you can implement a mechanism for automatic synchronization in the view without building complex and new JavaScript functions.

We use ng-The model directive binds the name property of the internal data model object ($scope) to the text input field.

The data model object refers to the $scope object. The $scope object is a simple JavaScript object, whose properties can be accessed by the view and can also interact with the controller.
Two-way data binding means that if the view changes a value, the data model will observe this change through dirty checking, and if the data model changes a value, the view will also change and re-render.

Module

In AngularJS, modules are the main way to define an application. Modules contain the main application code and allow us to declare modules using the angular.module() method, which can accept two parameters: the first is the module name, and the second is the list of dependencies, which is the list of objects that can be injected into the module.

angular.module('myApp',[]);

Controller

In AngularJS, a controller is a function used to add additional functionality to the view scope. We use it to set the initial state of the scope object and add custom behavior.
When we create a new controller on the page, AngularJS will generate and pass a new $scope to this controller.

The main difference between AngularJS and other JavaScript frameworks is that controllers are not suitable for executing DOM operations, formatting, or data operations, as well as state maintenance operations beyond storing data models. It is just a bridge between the view and $scope.

Expression

The syntax of binding a variable to $scope using {{}} symbols is essentially an expression: {{expression}}. Any operation performed on the expression will be executed within its scope, so you can call those restricted in the scope within the expression, and perform operations such as loops, function calls, and applying variables to mathematical expressions.

This example uses technology

① Use bootstrap layout on the page, and the page is a bootstrap template

② Use the AngularJS front-end framework

③ Use SpringMVC on the backend

The function of the entire code is to submit the input content to the background after input, and then the background returns the data to display on the page, with validation prompts during submission.

Here, I list three ways to do this application

1.Global scope controller
2.Module division controller
3.Extract the controller from the background request to create a service

JSP code:

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
!DOCTYPE html
<html lang="zh-cn" ng-app="MyApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Interface Test</title>
!-- Bootstrap -->
<link href="css/bootstrap/bootstrap.min.css" rel="external nofollow" rel="stylesheet">
</head>
<body>
 <div ng-controller="keepController">
 <form name="testForm" novalidate>
 <div id="responseMsg" class="testMode" >
 <div>
  <h3>Authentication interface:</h3>
  <textarea required class="form-control" rows="3" id="authData" name="authData" ng-model="authData"></textarea>
  <span style="color:red" ng-show="testForm.authData.$dirty && testForm.authData.$invalid">
     <span ng-show="testForm.authData.$error.required">The authentication interface is required</span>
   </span>
   </div>
 <div>
  <h3>Data request interface:</h3>
  <textarea required class="form-control" rows="3" id="reqData" name="reqData" ng-model="reqData"></textarea>
  <span style="color:red" ng-show="testForm.reqData.$dirty && testForm.reqData.$invalid">
     <span ng-show="testForm.reqData.$error.required">The data request interface is required</span>
   </span>
 </div>
 <div style="text-align: right;margin-right: 20px;margin-top:10px;">
  <button class="btn btn-default" role="button" ng-click="keepTest()"
  ng-disabled="testForm.authData.$invalid ||
  testForm.reqData.$invalid"
  >Connect Test</button>
 </div>
 <div>{{ansInfo}}</div>
 </div>
 </form>
 </div>
 <script src="js/angularJS/angular.min.js"></script>
 <script type="text/javascript">
//1.Example of global scope
 /* function keepController($scope,$http) {
  $scope.keepTest= function(){
  var pData = {authData:$scope.authData,reqData:$scope.reqData};
    $http({method:'POST',url:'testKeep',params:pData}).
    success(function(response) {
     $scope.ansInfo = response.a;});
  };
 } */
//2.Modularized controller
 /*var app = angular.module('MyApp',[]);
  app.controller('keepController',function($scope,$http){
  $scope.keepTest= function(){
  var pData = {authData:$scope.authData,reqData:$scope.reqData};
    $http({method:'POST',url:'testKeep',params:pData}).
    success(function(response) {
     $scope.ansInfo=response.a;});
  }
 }); */
 //3.The controller extracted from the request service
 angular.module('myapp.services',[]).factory('testService',function($http){
  var runRequest = function(pData){
  return $http({method:'POST',url:'testKeep',params:pData});
  };
  return {
  events:function(pData){
   return runRequest(pData);
  }
  };
 });
 angular.module('MyApp',['myapp.services']).
  controller('keepController',function($scope,testService){
  $scope.keepTest= function(){
   var pData = {authData:$scope.authData,reqData:$scope.reqData};
   testService.events(pData).success(function(response){
   $scope.ansInfo=response.a;
   });
  };
 });
 </script>
 <script src="js/jquery.js"></script>
 <script src="js/bootstrap/bootstrap.min.js></script>
</body>
</html>

JAVA code:

@RequestMapping(value = "testKeep", produces = "text/plain;charset=UTF-8")
@ResponseBody
public String testKeep(HttpServletRequest request,
  HttpServletResponse response) {
 System.out.println(request.getParameter("authData"));
 System.out.println(request.getParameter("reqData"));
 JSONObject ja = new JSONObject();
 ja.put("a", "aaa");
 ja.put("b", "bbb");
 ja.put("c", "ccc");
 System.out.println("test:")+ja.toString());
 return ja.toString();
}

Readers who are interested in more content related to AngularJS can check the special topics on this site: 'Summary of AngularJS Directive Operation Skills', 'AngularJS Introduction and Advanced Tutorial', and 'Summary of AngularJS MVC Architecture'.

I hope the content described in this article will be helpful to everyone's AngularJS program design.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to notice#w3Please report any violations by sending an email to codebox.com (replace # with @ in the email address) and provide relevant evidence. Once verified, this site will immediately delete the infringing content.

You May Also Like