詳細(xì)分析使用AngularJS編程中提交表單的方式
在AngularJS出現(xiàn)之前,很多開(kāi)發(fā)者就面對(duì)了表單提交這一問(wèn)題。由于提交表單的方式繁雜而不同,很容易令人瘋掉……然而現(xiàn)在看來(lái),依然會(huì)讓人瘋掉。
今天,我們會(huì)看一下過(guò)去使用PHP方式提交的表單,現(xiàn)在如何將其轉(zhuǎn)換為使用Angular提交。使用Angular來(lái)處理表單,對(duì)我而言,是一個(gè)“啊哈”時(shí)刻(譯者:表示了解或發(fā)現(xiàn)某事物的喜悅)。即使它甚至都沒(méi)有涉及多少Angular表層的東西,但是它卻幫助用戶(hù)看到表單提交之后的潛力,并且理解兩種數(shù)據(jù)綁定方式。
我們會(huì)使用jQuery平臺(tái)來(lái)進(jìn)行這個(gè)處理過(guò)程。所以所要做的工作首先使用javascript。我們會(huì)提交表單,展示錯(cuò)誤信息,添加錯(cuò)誤類(lèi),并且在javascript中顯示和隱藏信息。
之后,我們會(huì)使用Angular。在使用之前,我們要做大部分所需的工作,并且我們之前所做的很多工作會(huì)非常容易。讓我們開(kāi)始吧。
簡(jiǎn)單的表單
我們會(huì)關(guān)注兩種提交表單的方式:
- 舊方法:jQuery和PHP提交表單
- 新方法:AngularJS和PHP提交表單
首先看一下我們的表單,超級(jí)簡(jiǎn)單:
形式要求
- 實(shí)現(xiàn)頁(yè)面無(wú)刷新表單處理
- 輸入姓名和超級(jí)英雄別名
- 如果有錯(cuò)誤,顯示錯(cuò)誤提示
- 如果輸入有誤,將輸入變成紅色
- 如果所有內(nèi)容ok,顯示成功提示
文檔結(jié)構(gòu)
在我們的展示中,僅需兩個(gè)文件
- index.html
- process.php
表單處理
讓我們新建一個(gè)PHP來(lái)處理表單。該頁(yè)面非常小并且使用POST方式提交數(shù)據(jù)。
處理表單:這對(duì)我們來(lái)說(shuō)并不是那么重要的。你可以使用其他你喜歡的語(yǔ)言來(lái)處理你的表單。
// 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);
為了返回我們的數(shù)據(jù)用于AJAX調(diào)用,我們需要使用echo和json_encode。這就是我們PHP表單處理所有需要做的操作。使用普通的jQuery AJAX或者Angular處理表單也是這樣的。
展示表單
讓我們創(chuàng)建一個(gè)HTML來(lái)展示我們的表單
<!-- 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來(lái)使表單看起來(lái)不是那么丑。使用Bootstrap語(yǔ)法規(guī)則,每個(gè)input下含有一個(gè)spot來(lái)展示我們文本的錯(cuò)誤信息。
使用jQuery提交表單
現(xiàn)在,讓我們來(lái)使用jQuery處理表單提交。我會(huì)將所有的代碼添加到空的<script>標(biāo)簽中
<!-- 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將數(shù)據(jù)發(fā)送至我們的表單的代碼,有檢查是否有錯(cuò)和顯示成功提示的代碼。除此之外,我們希望每次表單提交之后,過(guò)去的錯(cuò)誤信息都會(huì)被清除。確實(shí)是不少代碼。
現(xiàn)在,如果表單中含有錯(cuò)誤,則:
如果提交成功:
現(xiàn)在,讓我們看使用Angular來(lái)提交相同的表單。記住,我們不需要更改任何關(guān)于我們的PHP如何處理表單的內(nèi)容,我們的應(yīng)用依然會(huì)具備相同的功能(在同一個(gè)地方展示錯(cuò)誤和成功信息)。
使用Angular提交表單
我們準(zhǔn)備在之前使用的<script>標(biāo)簽中設(shè)置我們的Angular應(yīng)用。所以刪除里面的內(nèi)容,我們就可以開(kāi)始了。
設(shè)置一個(gè)Angular應(yīng)用
步驟為:
1. 加載Angular
2. 設(shè)置module
3. 這是controller
4. 將module和controller應(yīng)用于HTML
5. 設(shè)置雙向變量綁定
6. 這是錯(cuò)誤和信息
看起來(lái)好像是很多內(nèi)容,但是最終,我們會(huì)用非常少的代碼,并且看起來(lái)會(huì)非常簡(jiǎn)潔。另外,創(chuàng)建帶有更多輸入更大的表單,也會(huì)更容易。
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應(yīng)用的基礎(chǔ)。我們已經(jīng)加載了Angular,創(chuàng)建了組件模塊和控制器,并且將其應(yīng)用于我們的網(wǎng)站。
接下來(lái),我將展示雙向綁定是如何工作的。
雙向數(shù)據(jù)綁定
這是Angular的核心思想之一,也是功能最強(qiáng)大的內(nèi)容之一。在
我們?cè)贏ngular中將數(shù)據(jù)和變量綁定在一起,無(wú)論是javascript也好,view也罷,只要有改變,兩者皆變。 為了演示數(shù)據(jù)綁定,我們需要獲取表單的input來(lái)自動(dòng)填充變量formData。讓我們回到應(yīng)用于頁(yè)面的Angular控制器中。我們?cè)谶^(guò)一下$scope和$http。 $scope:控制器和視圖層之間的粘合劑?;旧?,變量使用$scope從我們的控制器和視圖層之間傳遞和往來(lái)。具體詳細(xì)的定義,請(qǐng)參見(jiàn)文檔。 $http:Angular服務(wù)來(lái)幫助我們處理POST請(qǐng)求。更多信息,請(qǐng)參見(jiàn)文檔。 使用數(shù)據(jù)綁定獲取變量 好了,閑話(huà)少說(shuō)。我們將這些討論應(yīng)用到表單中去。方法比上面討論的要簡(jiǎn)單。我們想Angular控制器和視圖中分別添加一行。 現(xiàn)在,我們已經(jīng)建立了一個(gè)formData對(duì)象。讓我們用表單數(shù)據(jù)來(lái)填充它。在顯示調(diào)用每個(gè)輸入和獲得val()之前,我們用ng-model綁定一個(gè)特殊的輸入到變量。 現(xiàn)在,既然Angular已經(jīng)將每個(gè)輸入綁到了formData。 當(dāng)你輸入每個(gè)輸入框,你可以看到formData對(duì)象被填充了!有沒(méi)有很酷! 你不必在view中使用$scope。一切被認(rèn)為是嵌入到$scope中的。 在我們的舊表單中,我們使用jQuery提交表單,像這樣$('form').submit()?,F(xiàn)在我們使用Angular稱(chēng)作ng-submit的特性。要想完成這個(gè),我們需要添加一個(gè)控制器函數(shù)來(lái)處理表單,然后告訴我們form使用這個(gè)控制器函數(shù): 現(xiàn)在我們的form知道提交時(shí)使用控制器函數(shù)了。既然已經(jīng)到位了,然我們用$http來(lái)處理表單吧。 處理表單的語(yǔ)法看起來(lái)跟原始方式很像。好處是我們不需要手動(dòng)抓取表單數(shù)據(jù),或者注入,隱藏,添加類(lèi)顯示錯(cuò)誤或成功信息。 這就是我們的表單!沒(méi)有添加或移除類(lèi)。我們需要每次提交表單時(shí)都清楚錯(cuò)誤。我們只需綁定變量和需要用到的視圖。這非常棒,因?yàn)樘幚砥饔脕?lái)處理數(shù)據(jù),而視圖用來(lái)顯示數(shù)據(jù). 有時(shí)能看到用POST方式提交在服務(wù)器中看不到數(shù)據(jù),這是因?yàn)閖Query和Angular的序列化和發(fā)送數(shù)據(jù)的方式不同。這歸結(jié)于你所使用的服務(wù)器語(yǔ)言和它理解Angular提交的數(shù)據(jù)的能力。 上面的代碼是應(yīng)用于PHP服務(wù)器的,jQuery對(duì)于$.param函數(shù)則是必需的。雖然實(shí)現(xiàn)上文中提到的內(nèi)容有非常多不使用jQuery的方法,但在本實(shí)例中,使用jQuery的唯一原因就是,它更簡(jiǎn)單。 下面簡(jiǎn)潔的語(yǔ)法將會(huì)基于你服務(wù)器端語(yǔ)言來(lái)工作。 簡(jiǎn)潔語(yǔ)法 這個(gè)例子是以字符串的方式發(fā)送數(shù)據(jù),并且發(fā)送你的頭信息。如果你不需要這些,并且希望Angular 的$http POST盡可能的簡(jiǎn)潔,我們可以使用簡(jiǎn)寫(xiě)方法: 絕對(duì)更簡(jiǎn)潔更容易記住方法。 $http 內(nèi)部控制器: 理想的,你可以將$http請(qǐng)求從controller移除到 service.這只是為了演示目的,我們將會(huì)盡快在service上進(jìn)行討論. 在視圖中顯示錯(cuò)誤和信息 我們將使用指令ng-show和ng-class來(lái)處理我們的視圖,Angular雙方括號(hào)允許我們將變量放置在我們需要的地方。 我們的表單完成了!通過(guò)強(qiáng)大的Angular,我們可以將這些愚蠢的顯示/隱藏的js代碼邏輯從視圖中移走 了。現(xiàn)在我們的js文件只用來(lái)處理數(shù)據(jù),并且視圖可以做它自己的事情了。 我們的類(lèi)和錯(cuò)誤/成功等提示信息將在可獲取時(shí)顯示而不可獲取時(shí)隱藏。當(dāng)我們無(wú)須再像使用老的javascript那樣擔(dān)心是否已經(jīng)考慮全面,這變得更加容易。你也無(wú)須再擔(dān)心是否記得隱藏每處form提交時(shí)的那些錯(cuò)誤信息。 Angular表單驗(yàn)證 獲取更多表單驗(yàn)證的信息,請(qǐng)研讀我們另一文章:AngularJS Form Validation。 現(xiàn)在我們已把美觀的表單全部轉(zhuǎn)變?yōu)锳ngular的了。我們共同學(xué)習(xí)了許多概念,希望你與它們接觸更多,它們也將更易用。 回顧: 這些Angular技術(shù)將在更龐大的應(yīng)用中使用,你可以用它們創(chuàng)建許多好東西。祝Angular之途愉快,敬請(qǐng)期待更多深入的文章。同時(shí),你也可以通過(guò)深入了解其指南,服務(wù)和廠商等來(lái)繼續(xù)學(xué)習(xí)Angular。
<!-- 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 = {};
}
...
<!-- 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="formData.name">
<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>
...
處理表單
<!-- 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()">
...
<!-- 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 = data.errors.name;
$scope.errorSuperhero = data.errors.superheroAlias;
} else {
// if successful, bind success message to message
$scope.message = data.message;
}
});
};
...
jQuery POST vs Angular POST
...
$http.post('process.php', $scope.formData)
.success(function(data) {
...
});
...
<!-- 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>
...
結(jié)束語(yǔ)
相關(guān)文章
AngularJS ng-change 指令的詳解及簡(jiǎn)單實(shí)例
本文主要介紹AngularJS ng-change 指令,這里對(duì)ng-change指令資料做了詳細(xì)介紹,并提供源碼和運(yùn)行結(jié)果,有需要的小伙伴參考下2016-07-07AngularJS實(shí)現(xiàn)與后臺(tái)服務(wù)器進(jìn)行交互的示例講解
今天小編就為大家分享一篇AngularJS實(shí)現(xiàn)與后臺(tái)服務(wù)器進(jìn)行交互的示例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-08-08詳解Angular組件數(shù)據(jù)不能實(shí)時(shí)更新到視圖上的問(wèn)題
這篇文章主要為大家介紹了Angular組件數(shù)據(jù)不能實(shí)時(shí)更新到視圖上的問(wèn)題詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10詳解angular2.x創(chuàng)建項(xiàng)目入門(mén)指令
這篇文章主要介紹了詳解angular2.x創(chuàng)建項(xiàng)目入門(mén)指令,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-10-10spring+angular實(shí)現(xiàn)導(dǎo)出excel的實(shí)現(xiàn)代碼
這篇文章主要介紹了spring+angular實(shí)現(xiàn)導(dǎo)出excel的實(shí)現(xiàn)代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-02-02