Angular 可使用指令無縫地增強標準表單元素的功能,我們將討論它的優點,包括:
數據綁定、建立模型屬性、驗證表單、驗證表單後反饋信息、表單指令屬性
下面我們通過案例驗證他們的用法:
一、雙向數據綁定(ng-model)和建立模型屬性
<!DOCTYPE><!-- use module --><html ng-app="exampleApp"><head> <title>Angular Directive</title> <meta charset="utf-8"/> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css"></head><body><!-- 案例:雙向數據綁定--><div ng-controller="defaultCtrl"> <!-- 過濾complete為false的項--> <h3>To Do List<span>{{(todos | filter : {complete : 'false'}).length}}</span></h3> <div> <div> <div> <label for="action">Action: </label> <!-- ng-model 雙向綁定--> <!-- 雙向數據綁定:數據模型(Module)和視圖(View)之間的雙向綁定。 --> <!-- 當其中一方發送更替後,另一個也發生變化--> <input type="text" id="action" ng-model="newToDo.action"> </div> <div> <label for="location">Location: </label> <select id="location" ng-model="newToDo.location"> <option>Home</option> <option>Office</option> <option>Mall</option> </select> </div> <!-- ng-click點擊Add添加項目--> <button ng-click="addNewItem(newToDo)">Add</button> </div> <div> <table> <thead> <tr><th>#</th><th>Action</th><th>Done</th></tr> </thead> <tbody> <tr ng-repeat="item in todos"> <!-- $index默認為0,遞增--> <td>{{$index + 1}}</td> <td>{{item.action}}</td> <td> <input type="checkbox" ng-model="item.complete"/> </td> </tr> </tbody> </table> </div> </div></div><script type="text/javascript" src="js/angular.min.js"></script><script type="text/javascript">// define a module named exampleAppangular.module("exampleApp", []) // define a controller named defaultCtrl .controller('defaultCtrl', function ($scope) { // 數據模型$scope.todos = [ { action : "play ball", complete : false }, { action : "singing", complete : false }, { action : "running", complete : true }, { action : "dance", complete : true }, { action : "swimming", complete : false }, { action : "eating", complete : false }, ]; // 添加數據到模型$scope.addNewItem = function (newItem) { // 判斷是否存在if (angular.isDefined(newItem) && angular.isDefined(newItem.action) && angular.isDefined(newItem.location)) { $scope.todos.push({ action : newItem.action + " (" + newItem.location + ")", complete : false }) } } })</script></body></html>首先定義了數據模型scope.todos和添加數據到模型的addNewItem()方法,接著使用雙向數據綁定ng−model將視圖中表單的action和location和模型中的scope.todos進行綁定,
最後通過ng-click點擊屬性觸發添加數據到模型的addNewItem()方法完成操作
二、驗證表單
在我們提交表單到服務器之前,我們需要來檢測一下用戶提交的數據是否存在或者是說合法,否則提交無用的數據會浪費資源。
<!DOCTYPE><!-- use module --><html ng-app="exampleApp"><head> <title>Angular Directive</title> <meta charset="utf-8"/> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css"> <style> </style></head><body><div id="todoPanel" ng-controller="defaultCtrl"> <!-- novalidate表示拋棄瀏覽器自帶的表單驗證,用NG自己的驗證--> <!-- ng-submit="addUser(newUser) 當表單數據合法時,提交數據到模型--> <form name="myForm" novalidate ng-submit="addUser(newUser)"> <div> <div> <label>Name:</label> <!-- required 表該表單必填--> <!-- ng-model="newUser.name" 雙向數據綁定--> <input name="userName" type="text" required ng-model="newUser.name"> </div> <div> <label>Email:</label> <input name="userEmail" type="email"required ng-model="newUser.email"> </div> <div> <label> <input name="agreed" type="checkbox"ng-model="newUser.agreed" required> I agree to the terms and conditions </label> </div> <!-- g-disabled="myForm.$invalid" 當前面填寫表單中的任意一項不合法時,該提交按鈕都是不可用的--> <button type="submit" ng-disabled="myForm.$invalid"> OK </button> </div> <div> Message: {{message}} <div> Valid: {{myForm.$valid}} </div> </div> </form></div><script type="text/javascript" src="js/angular.min.js"></script><script type="text/javascript">angular.module("exampleApp", []) .controller("defaultCtrl", function ($scope) { // 添加用戶數據到模型$scope.message $scope.addUser = function (userDetails) { $scope.message = userDetails.name + " (" + userDetails.email + ") (" + userDetails.agreed + ")"; } // 顯示驗證前後的結果$scope.message = "Ready";});</script></body></html>首先定義了數據模型scope.message和添加數據到模型的addUser()方法,接著在視圖中添加表單元素validate、name屬性和ng−submit屬性隨後使用雙向數據綁定ng−model將視圖中表單的action和location和模型中的scope.todos進行綁定,且使用驗證屬性required和email表單
之後對提交按鈕進行禁用,僅當表單數據全部合法才能用,不合法都禁用(ng-disabled=”myForm.$invalid”)
最後通過ng-submit屬性提交數據到模型的addUser()方法完成操作
三、表單驗證反饋信息
我們僅僅對錶單進行驗證是遠遠不夠的,因為用戶不知道為什麼出錯而感到困惑,因此我們需要反饋信息給用戶,讓他們明白該填寫什麼
先介紹一下NG中要驗證的類
ng-pristine用戶沒交互元素被添加到這個類
ng-dirty 用戶交互過元素被添加到這個類
ng-valid 驗證結果有效元素被添加到這個類
ng-invalid 驗證結果無效元素被添加到這個類
<!DOCTYPE><!-- use module --><html ng-app="exampleApp"><head> <title>Angular Directive</title> <meta charset="utf-8"/> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css"> <style> /*交互且必填樣式*/ form.validate .ng-invalid-required.ng-dirty { background-color: orange; } /*交互不合法樣式*/ form .ng-invalid.ng-dirty { background-color: lightpink; } /*郵件不合法且交互過*/ form.validate .ng-invalid-email.ng-dirty { background-color: lightgoldenrodyellow; } div.error{ color: red; font-weight: bold; } div.summary.ng-valid{ color: green; font-weight: bold; } div.summary.ng-invalid{ color: red; font-weight: bold; } </style></head><body><!-- 案例:雙向數據綁定--><div ng-controller="defaultCtrl"> <!-- novalidate="novalidate" 僅僅NG表單驗證--> <!-- ng-submit="addUser(newUser)" 添加數據到模型--> <!-- ng-class="showValidation ? 'validate' : '' 當驗證合法,showValidation為true,這是觸發ng-class為validate --> <form name="myForm" novalidate="novalidate" ng-submit="addUser(newUser)" ng-class="showValidation ? 'validate' : ''"> <div> <div> <label>Email: </label> <input name="email" type="email" required="required" ng-model="newUser.email"> <!-- 驗證提示信息--> <div> <!-- 顯示反饋信息--> <span ng-class="error" ng-show="showValidation"> {{getError(myForm.email.$error)}} </span> </div> </div> <button type="submit" >OK</button> <div> Message : {{message}} <!-- 當myForm.$valid驗證合法,showValidation為true,這是觸發ng-class為ng-valid,否則,ng-invalid --> <div ng-class="myForm.$valid ? 'ng-valid' : 'ng-invalid'" > Valid : {{myForm.$valid}} </div> </div> </form></div><script type="text/javascript" src="js/angular.min.js"></script><script type="text/javascript">// define a module named exampleAppangular.module("exampleApp", []) // define a controller named defaultCtrl .controller('defaultCtrl', function ($scope) { // 添加數據到模型$scope.addUser = function (userDetails) { if (myForm.$valid) { $scope.message = userDetails.name + " (" + userDetails.email + ") (" + userDetails.agreed + ")"; } else { $scope.showValidation = true; } } // 數據模型$scope.message = "Ready"; // 錯誤反饋信息// 當沒有填寫信息時,提示Please enter a value // 當驗證出錯時,提示Please enter a valid email address $scope.getError = function (error) { if (angular.isDefined(error)) { if (error.required) { return "Please enter a value"; } else if (error.email) { return "Please enter a valid email address"; } } } })</script></body></html>首先在style中定義反饋信息的樣式、表單驗證的樣式
接著在JS中寫入錯誤時反饋的信息
最後在視圖中綁定ng-class
四、表單指令屬性
1.使用input元素
<!DOCTYPE><!-- use module --><html ng-app="exampleApp"><head> <title>Angular Directive</title> <meta charset="utf-8"/> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css"> <style> </style></head><body><div id="todoPanel" ng-controller="defaultCtrl"> <form name="myForm" novalidate="novalidate"> <div> <div> <label>Text: </label> <!-- ng-required="requireValue" 通過數據綁定required值--> <!-- ng-minlength="3" ng-maxlength="10" 允許最大最小字符--> <!-- ng-pattern="matchPattern" 正則匹配--> <input name="sample" ng-model="inputValue" ng-required="requireValue" ng-minlength="3" ng-maxlength="10" ng-pattern="matchPattern"> </div> </div> <div> <!-- 必填--> <p>Required Error: {{myForm.sample.$error.required}}</p> <!-- 最小最大長度--> <p>Min Length Error: {{myForm.sample.$error.minlength}}</p> <p>Max Length Error: {{myForm.sample.$error.maxlength}}</p> <!-- 只匹配小寫字母--> <p>Pattern Error: {{myForm.sample.$error.pattern}}</p> <!-- 驗證合法--> <p>Element Valid: {{myForm.sample.$valid}}</p> </div> </form></div><script type="text/javascript" src="js/angular.min.js"></script><script type="text/javascript">// define a module named exampleAppangular.module("exampleApp", []) // define a controller named defaultCtrl .controller('defaultCtrl', function ($scope) { $scope.requireValue = true; $scope.matchPattern = new RegExp("^[az]"); })</script></body></html>2.選擇列表
<!DOCTYPE><!-- use module --><html ng-app="exampleApp"><head> <title>Angular Directive</title> <meta charset="utf-8"/> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css"> <style> </style></head><body><div id="todoPanel" ng-controller="defaultCtrl"> <form name="myForm" novalidate="novalidate"> <div> <div> <label>Selection an action: </label> <!-- 遍歷列表按照item.place排序item.id as item.action 改變選項值--> <!-- ng-options="item.id as item.action group by item.place for item in todos" --> <select ng-model="selectValue" ng-options="item.id as item.action group by item.place for item in todos"> <option value="">(Pick One)</option> </select> </div> </div> <div> <p>Selected: {{selectValue || "None"}}</p> </div> </form></div><script type="text/javascript" src="js/angular.min.js"></script><script type="text/javascript">// define a module named exampleAppangular.module("exampleApp", []) // define a controller named defaultCtrl .controller('defaultCtrl', function ($scope) { // 模型數據$scope.todos = [ { id : 100, place : "School", action : "play ball", complete : false }, { id : 200, place : "Home", action : "eating", complete : false }, { id : 300, place : "Home", action : "watch TV", complete : true } ]; })</script></body></html>以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。