English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Este artículo ilustra la presentación de formulario de AngularJS. Compartimoslo con todos para referencia, como se detalla a continuación:
El enlace de datos en AngularJS
AngularJS crea plantillas en tiempo real para reemplazar la vista, en lugar de combinar los datos en la plantilla y actualizar el DOM. Cualquier valor en un componente de vista independiente se reemplaza dinámicamente.
ng-La propiedad app declara que todo el contenido que la contiene pertenece a esta aplicación AngularJS,这也是 podemos anidar aplicaciones AngularJS en aplicaciones web. Solo el contenido que tiene ng-Los elementos del elemento DOM que contienen la propiedad app son los que se ven afectados por AngularJS.
Cuando AngularJS considera que un valor puede cambiar, ejecuta su propio ciclo de eventos para verificar si este valor se ha vuelto 'sucio'. Si este valor ha cambiado desde la última ejecución del ciclo de eventos, se considera un valor 'sucio'. Esto es también la manera en que Angular puede rastrear y responder a los cambios en la aplicación.
Este proceso se llama verificación de suciedad. La verificación de suciedad es una manera efectiva de verificar los cambios en el modelo de datos. Cuando hay cambios potenciales, AngularJS ejecuta la verificación de suciedad en el ciclo de eventos para garantizar la consistencia de los datos.
Gracias a AngularJS, no es necesario construir nuevas funciones JavaScript complejas para implementar el mecanismo de sincronización automática de clases en la vista.
Usamos ng-La instrucción model enlaza la propiedad name del objeto modelo de datos interno ($scope) al campo de entrada de texto.
El objeto modelo de datos es el objeto $scope. El objeto $scope es un objeto JavaScript simple, en el que las propiedades pueden ser accedidas por la vista y pueden interactuar con el controlador.
El enlace de datos bidireccional significa que si el vista cambia un valor, el modelo de datos observará este cambio a través de la verificación de suciedad, y si el modelo de datos cambia un valor, la vista también se volverá a renderizar con un cambio.
模块
在AngularJS中,模块是定义应用的最主要的方式。模块包含了主要的应用代码,它允许我们使用angular.module()方法来声明模块,这个方法能够接受两个参数,第一个是模块的名称,第二个是依赖列表,也就是可以被注入到模块中的对象列表。
angular.module('myApp',[]);
控制器
AngularJS中的控制器是一个函数,用来向视图的作用域中添加额外的功能。我们用它来给作用域对象设置初始状态,并添加自定义行为。
当我们在页面上创建一个新的控制器时,AngularJS会生成并传递一个新的$scope给这个控制器。
AngularJS与其他JavaScript框架最主要的一个区别就是,控制器并不适合用来执行DOM操作、格式化或数据操作,以及除存储数据模型之外的状态维护操作。它只是视图和$scope之间的桥梁。
表达式
用{{}}符号将一个变量绑定到$scope上的写法本质上就是一个表达式:{{expression}}。对表达式进行的任何操作,都会在其所属的作用域内部执行,因此可以在表达式内部调用那些限制在此作用域内的bianl,并进行循环、函数调用、将变量应用到数学表达式中等操作。
本例子采用技术
① 页面使用bootstrap布局,页面是bootstrap的模板
② 前端框架AngularJS
③ 后台使用SpringMVC
整个代码的功能是在输入内容后,提交给后台,后台再返回数据显示到页面,提交时有验证提示。
我在这里列举了三种方式来做这次应用
1.全局作用域的控制器
2.模块划分的控制器
3.将后台请求做成服务抽离出来的控制器
JSP代码:
<%@ 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>Pruebas de interfaz</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>Interfaz de autenticación:</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">La interfaz de autenticación es obligatoria</span> </span> </div> <div> <h3>Interfaz de solicitud de datos:</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">Los datos de solicitud de datos son obligatorios</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" >Conectar prueba</button> </div> <div>{{ansInfo}}</div> </div> </form> </div> <script src="js/angularJS/angular.min.js"></script> <script type="text/javascript"> //1.全局作用域的例子 /* 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.模块化控制器 /*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.请求服务抽出来的控制器 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, and 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#oldtoolbag.com (when sending an email, please replace # with @ to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)