使用Angular提交表單


使用Angular提交表單

我們准備在之前使用的<script>標簽中設置我們的Angular應用。所以刪除里面的內容,我們就可以開始了。

設置一個Angular應用

步驟為:

    1. 加載Angular

    2. 設置module

    3. 這是controller

    4. 將module和controller應用於HTML

    5. 設置雙向變量綁定

    6. 這是錯誤和信息

看起來好像是很多內容,但是最終,我們會用非常少的代碼,並且看起來會非常簡潔。另外,創建帶有更多輸入更大的表單,也會更容易。

Angular 組件和控制器

首先,加載Angular並且新建組件和控制器

<!-- index.html -->

 

...

 

    <!-- LOAD JQUERY -->

    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

    <!-- LOAD ANGULAR -->

    <script src="//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">

 

...

現在,我們有了Angular應用的基礎。我們已經加載了Angular,創建了組件模塊和控制器,並且將其應用於我們的網站。

接下來,我將展示雙向綁定是如何工作的。

雙向數據綁定

這是Angular的核心思想之一,也是功能最強大的內容之一。在Angular文檔中,我們看到:“在Angular網頁應用中的數據綁定,是模型和視圖層之間的數據自動同步。”這意味着,我們需要在表單中抓取數據,使用$('input[name=name]').val()並不是必需的。

我們在Angular中將數據和變量綁定在一起,無論是JavaScript也好,view也罷,只要有改變,兩者皆變。

為了演示數據綁定,我們需要獲取表單的input來自動填充變量formData。讓我們回到應用於頁面的Angular控制器中。我們在過一下$scope和$http。

$scope:控制器和視圖層之間的粘合劑。基本上,變量使用$scope從我們的控制器和視圖層之間傳遞和往來。具體詳細的定義,請參見文檔

$http:Angular服務來幫助我們處理POST請求。更多信息,請參見文檔

使用數據綁定獲取變量

好了,閑話少說。我們將這些討論應用到表單中去。方法比上面討論的要簡單。我們想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 = {};

 

        }

 

...

現在,我們已經建立了一個formData對象。讓我們用表單數據來填充它。在顯示調用每個輸入和獲得val()之前,我們用ng-model綁定一個特殊的輸入到變量。

<!-- 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>

 

...

現在,既然Angular已經將每個輸入綁到了formData。 當你輸入每個輸入框,你可以看到formData對象被填充了!有沒有很酷!

你不必在view中使用$scope。一切被認為是嵌入到$scope中的。

處理表單

在我們的舊表單中,我們使用jQuery提交表單,像這樣$('form').submit()。現在我們使用Angular稱作ng-submit的特性。要想完成這個,我們需要添加一個控制器函數來處理表單,然后告訴我們form使用這個控制器函數:

<!-- 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()">

 

...

現在我們的form知道提交時使用控制器函數了。既然已經到位了,然我們用$http來處理表單吧。

處理表單的語法看起來跟原始方式很像。好處是我們不需要手動抓取表單數據,或者注入,隱藏,添加類顯示錯誤或成功信息。

<!-- 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

有時能看到用POST方式提交在服務器中看不到數據,這是因為jQuery和Angular的序列化和發送數據的方式不同。這歸結於你所使用的服務器語言和它理解Angular提交的數據的能力。

上面的代碼是應用於PHP服務器的,jQuery對於$.param函數則是必需的。雖然實現上文中提到的內容有非常多不使用jQuery的方法,但在本實例中,使用jQuery的唯一原因就是,它更簡單。

下面簡潔的語法將會基於你服務器端語言來工作。更多關於AngularJS AJAX調用的信息,歡迎閱讀這篇非常棒的文章:Make AngularJS $http Service Behave Like jQuery AJAX

簡潔語法

這個例子是以字符串的方式發送數據,並且發送你的頭信息。如果你不需要這些,並且希望Angular 的$http POST盡可能的簡潔,我們可以使用簡寫方法:

...

    $http.post('process.php', $scope.formData)

        .success(function(data) {

            ...

        });

...

絕對更簡潔更容易記住方法。

$http 內部控制器: 理想的,你可以將$http請求從controller移除到 service.這只是為了演示目的,我們將會盡快在service上進行討論.

在視圖中顯示錯誤和信息

我們將使用指令ng-show和ng-class來處理我們的視圖,Angular雙方括號允許我們將變量放置在我們需要的地方。

ng-show: 根據變量值是否存在來顯示或隱藏元素. 文檔
ng-class: 根據變量值是否存在(或一些其他表達式)來添加或移除類. 文檔

<!-- 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>

 

...

我們的表單完成了!通過強大的Angular,我們可以將這些愚蠢的顯示/隱藏的js代碼邏輯從視圖中移走 了。現在我們的js文件只用來處理數據,並且視圖可以做它自己的事情了。

我們的類和錯誤/成功等提示信息將在可獲取時顯示而不可獲取時隱藏。當我們無須再像使用老的javascript那樣擔心是否已經考慮全面,這變得更加容易。你也無須再擔心是否記得隱藏每處form提交時的那些錯誤信息。

Angular表單驗證 獲取更多表單驗證的信息,請研讀我們另一文章:AngularJS Form Validation

結束語

現在我們已把美觀的表單全部轉變為Angular的了。我們共同學習了許多概念,希望你與它們接觸更多,它們也將更易用。

回顧:

  • 創建一個Angular module

  • 創建一個Angular controller

  • 雙向數據綁定

  • ng-model綁定inputs

  • ng-click提交表單

  • 使用雙向數據綁定展示表單錯誤

  • 展示一個基於是否變量存在的div

  • 添加一個基於是否變量存在的類

這些Angular技術將在更龐大的應用中使用,你可以用它們創建許多好東西。祝Angular之途愉快,敬請期待更多深入的文章。同時,你也可以通過深入了解其指南,服務和廠商等來繼續學習Angular。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM