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