1、簡單實例
<div ng-app="xxApp" ng-controller="xxCtrl">
<form novalidate>
First Name: <input type="text" ng-model="user">
<br>
<button ng-click="reset()">reset</button>
</form>
<p>表單值:{{user}}</p>
<p>默認值:{{default}}</p>
</div>
<script>
var app = angular.module('xxApp', []);
app.controller('xxCtrl', function($scope) {
$scope.default = "Evan Lee";
$scope.reset = function() {
$scope.user = angular.copy($scope.default);
};
$scope.reset();
});
</script>
輸出:
2、輸入驗證
$dirty 表單有填寫記錄 $valid 字段內容合法
$pristine 表單沒有填寫記錄 $invalid 字段內容非法
<!-- 表單屬性 novalidate 用於禁用瀏覽器默認的驗證。 -->
<form ng-app="xxApp" ng-controller="xxCtrl" name="xxForm" novalidate>
<p>用戶名:
<input type="text" name="user" ng-model="user" required>
<span style="color:red" ng-show="xxForm.user.$dirty && xxForm.user.$invalid">
<span ng-show="xxForm.user.$error.required">用戶名不能爲空</span>
</span>
</p>
<p>郵 箱:
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="xxForm.email.$dirty && xxForm.email.$invalid">
<span ng-show="xxForm.email.$error.required">郵箱不能爲空</span>
<span ng-show="xxForm.email.$error.email">非法的郵箱地址!</span>
</span>
</p>
<p>
<input type="submit"
ng-disabled="xxForm.user.$dirty && xxForm.user.$invalid ||
xxForm.email.$dirty && xxForm.email.$invalid">
</p>
</form>
<script>
var app = angular.module('xxApp', []);
app.controller('xxCtrl', function($scope) {
$scope.user = 'Evan Lee';
$scope.email = '[email protected]';
});
</script>
輸出: