詳細分析使用AngularJS編程中提交表單的方式
在AngularJS出現(xiàn)之前,很多開發(fā)者就面對了表單提交這一問題。由于提交表單的方式繁雜而不同,很容易令人瘋掉……然而現(xiàn)在看來,依然會讓人瘋掉。
今天,我們會看一下過去使用PHP方式提交的表單,現(xiàn)在如何將其轉換為使用Angular提交。使用Angular來處理表單,對我而言,是一個“啊哈”時刻(譯者:表示了解或發(fā)現(xiàn)某事物的喜悅)。即使它甚至都沒有涉及多少Angular表層的東西,但是它卻幫助用戶看到表單提交之后的潛力,并且理解兩種數據綁定方式。
我們會使用jQuery平臺來進行這個處理過程。所以所要做的工作首先使用javascript。我們會提交表單,展示錯誤信息,添加錯誤類,并且在javascript中顯示和隱藏信息。
之后,我們會使用Angular。在使用之前,我們要做大部分所需的工作,并且我們之前所做的很多工作會非常容易。讓我們開始吧。
簡單的表單
我們會關注兩種提交表單的方式:
- 舊方法:jQuery和PHP提交表單
- 新方法:AngularJS和PHP提交表單
首先看一下我們的表單,超級簡單:

形式要求
- 實現(xiàn)頁面無刷新表單處理
- 輸入姓名和超級英雄別名
- 如果有錯誤,顯示錯誤提示
- 如果輸入有誤,將輸入變成紅色
- 如果所有內容ok,顯示成功提示
文檔結構
在我們的展示中,僅需兩個文件
- index.html
- process.php
表單處理
讓我們新建一個PHP來處理表單。該頁面非常小并且使用POST方式提交數據。
處理表單:這對我們來說并不是那么重要的。你可以使用其他你喜歡的語言來處理你的表單。
// 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);
為了返回我們的數據用于AJAX調用,我們需要使用echo和json_encode。這就是我們PHP表單處理所有需要做的操作。使用普通的jQuery AJAX或者Angular處理表單也是這樣的。
展示表單
讓我們創(chuàng)建一個HTML來展示我們的表單
<!-- index.html --> <!doctype html> <html> <head> <title>Angular Forms</title> <!-- LOAD BOOTSTRAP CSS --> <link rel="stylesheet" > <!-- LOAD JQUERY --> <!-- when building an angular app, you generally DO NOT want to use jquery --> <!-- we are breaking this rule here because jQuery's $.param will help us send data to our PHP script so that PHP can recognize it --> <!-- this is jQuery's only use. avoid it in Angular apps and if anyone has tips on how to send data to a PHP script w/o jQuery, please state it in the comments --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <!-- PROCESS FORM WITH AJAX (OLD) --> <script> <!-- WE WILL PROCESS OUR FORM HERE --> </script> </head> <body> <div class="container"> <div class="col-md-6 col-md-offset-3"> <!-- PAGE TITLE --> <div class="page-header"> <h1><span class="glyphicon glyphicon-tower"></span> Submitting Forms with Angular</h1> </div> <!-- SHOW ERROR/SUCCESS MESSAGES --> <div id="messages"></div> <!-- FORM --> <form> <!-- NAME --> <div id="name-group" class="form-group"> <label>Name</label> <input type="text" name="name" class="form-control" placeholder="Bruce Wayne"> <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"> <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> </div> </div> </body> </html>
現(xiàn)在,我們有了表單。我們另外還使用了Bootstrap來使表單看起來不是那么丑。使用Bootstrap語法規(guī)則,每個input下含有一個spot來展示我們文本的錯誤信息。

使用jQuery提交表單
現(xiàn)在,讓我們來使用jQuery處理表單提交。我會將所有的代碼添加到空的<script>標簽中
<!-- 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 (data.errors.name) {
$('#name-group').addClass('has-error');
$('#name-group .help-block').html(data.errors.name);
}
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>
...
這里處理表單有不少的代碼。我們有獲取表單中變量的代碼,有使用AJAX將數據發(fā)送至我們的表單的代碼,有檢查是否有錯和顯示成功提示的代碼。除此之外,我們希望每次表單提交之后,過去的錯誤信息都會被清除。確實是不少代碼。
現(xiàn)在,如果表單中含有錯誤,則:

如果提交成功:

現(xiàn)在,讓我們看使用Angular來提交相同的表單。記住,我們不需要更改任何關于我們的PHP如何處理表單的內容,我們的應用依然會具備相同的功能(在同一個地方展示錯誤和成功信息)。
使用Angular提交表單
我們準備在之前使用的<script>標簽中設置我們的Angular應用。所以刪除里面的內容,我們就可以開始了。
設置一個Angular應用
步驟為:
1. 加載Angular
2. 設置module
3. 這是controller
4. 將module和controller應用于HTML
5. 設置雙向變量綁定
6. 這是錯誤和信息
看起來好像是很多內容,但是最終,我們會用非常少的代碼,并且看起來會非常簡潔。另外,創(chuàng)建帶有更多輸入更大的表單,也會更容易。
Angular 組件和控制器
首先,加載Angular并且新建組件和控制器
<!-- index.html -->
...
<!-- LOAD JQUERY -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<!-- LOAD ANGULAR -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></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>
</head>
<!-- apply the module and controller to our body so angular is applied to that -->
<body ng-app="formApp" ng-controller="formController">
...
現(xiàn)在,我們有了Angular應用的基礎。我們已經加載了Angular,創(chuàng)建了組件模塊和控制器,并且將其應用于我們的網站。
接下來,我將展示雙向綁定是如何工作的。
雙向數據綁定
相關文章
淺析如何利用angular結合translate為項目實現(xiàn)國際化
利用angular進行國際化轉換時利用【ng-bind-html】來進行語言的翻譯是接近幾乎比較完美的方案,不會像利用【{{}}】模式,當頁面加載緩慢時導致頁面太丑。本文對其實現(xiàn)方法進行介紹,有需要的朋友可以看下2016-12-12
AngularJS使用angular-formly進行表單驗證
這篇文章主要介紹了AngularJS使用angular-formly進行表單驗證的相關資料,需要的朋友可以參考下2015-12-12
在Angular中實現(xiàn)一個級聯(lián)效果的下拉框的示例代碼
這篇文章主要介紹了在Angular中實現(xiàn)一個級聯(lián)效果的下拉框的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-05-05
關于AngularJS中幾種Providers的區(qū)別總結
這篇文章主要給大家介紹了關于AngularJS中幾種Providers的區(qū)別的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用AngularJS具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2020-05-05
angular5 httpclient的示例實戰(zhàn)
本篇文章主要介紹了angular5 httpclient的示例實戰(zhàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03

