AngularJS提供豐富填寫表單和驗證。我們可以用ng-click來處理AngularJS點擊按鈕事件,然後使用 $dirty 和 $invalid標誌做驗證的方式。使用novalidate表單聲明禁止任何瀏覽器特定的驗證。表單控制項使用了大量的角落活動。讓我們快速瀏覽一下有關事件先。
事件
AngularJS提供可與HTML控制項相關聯的多個事件。例如ng-click通常與按鈕相關聯。以下是AngularJS所支持的事件。
ng-click
使用點選一個按鈕的指令,表單重設資料。
<input name="firstname" type="text" ng-model="firstName" required> <input name="lastname" type="text" ng-model="lastName" required> <input name="email" type="email" ng-model="email" required> <button ng-click="reset()">Reset</button> <script> function studentController($scope) { $scope.reset = function(){ $scope.firstName = "Mahesh"; $scope.lastName = "Parashar"; $scope.email = "MaheshParashar@yiibai.com"; } $scope.reset(); } </script>
驗證資料
可使用下面追蹤誤差。
範例
下面的範例將展示上述所有指令。
testAngularJS.html
<html> <head> <title>Angular JS Forms</title> <style> table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f2f2f2; } table tr:nth-child(even) { background-color: #ffffff; } </style> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app="" ng-controller="studentController"> <form name="studentForm" novalidate> <table border="0"> <tr><td>Enter first name:</td><td><input name="firstname" type="text" ng-model="firstName" required> <span style="color:red" ng-show="studentForm.firstname.$dirty && studentForm.firstname.$invalid"> <span ng-show="studentForm.firstname.$error.required">First Name is required.</span> </span> </td></tr> <tr><td>Enter last name: </td><td><input name="lastname" type="text" ng-model="lastName" required> <span style="color:red" ng-show="studentForm.lastname.$dirty && studentForm.lastname.$invalid"> <span ng-show="studentForm.lastname.$error.required">Last Name is required.</span> </span> </td></tr> <tr><td>Email: </td><td><input name="email" type="email" ng-model="email" length="100" required> <span style="color:red" ng-show="studentForm.email.$dirty && studentForm.email.$invalid"> <span ng-show="studentForm.email.$error.required">Email is required.</span> <span ng-show="studentForm.email.$error.email">Invalid email address.</span> </span> </td></tr> <tr><td><button ng-click="reset()">Reset</button></td><td><button ng-disabled="studentForm.firstname.$dirty && studentForm.firstname.$invalid || studentForm.lastname.$dirty && studentForm.lastname.$invalid || studentForm.email.$dirty && studentForm.email.$invalid" ng-click="submit()">Submit</button></td></tr> </table> </form> </div> <script> function studentController($scope) { $scope.reset = function(){ $scope.firstName = "Mahesh"; $scope.lastName = "Parashar"; $scope.email = "MaheshParashar@yiibai.com"; } $scope.reset(); } </script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </body> </html>
輸出
在網頁瀏覽器開啟textAngularJS.html。看到結果如下。