标签:
点击查看AngularJS系列目录
转载请注明出处:http://www.cnblogs.com/leosx/
input, select, textarea控件都是给用户输入数据用的。窗体和控件提都提供了验证服务,使得在用户输入了无效数据的情况下,提交表单之前就可以得到知道。这样的验证远远比只在服务端进行验证好得多,因为在前端验证,用户可以得到很好的用户输入错误的反馈!提高用户体验。请记住,在客户端进行验证是用户体验的非常重要的组成部分。但是它很容易就可以被篡改,所以我们是不能信赖前端验证的,后端依旧得进行验证。
文件一:index.html
<div ng-controller="ExampleController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="update(user)" value="Save" />
</form>
<pre>user = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
angular.module(‘formExample‘, [])
.controller(‘ExampleController‘, [‘$scope‘, function($scope) {
$scope.master = {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}]);
</script>
效果图:
当点击Reset按钮的时候,就会把user对象给重置为原来保存的对象。
请注意:novalidate 用来禁用掉原生的浏览器表单验证。如果验证不通过,那么ngModel 所绑定的model的对应值是不会改变的。
使用样式,我们可以更好的控制表单控件,例如:ngModel 指令就为对应的元素增加了如下样式:
1、
ng-valid: 模型(model)验证通过2、
ng-invalid: 模型(model)验证失败3、
ng-valid-[key]: 通过$setValidity增加的验证通过的密匙()4、
ng-invalid-[key]: 通过$setValidity增加的验证失败的密匙5、
ng-pristine: 还没有与controller进行互动。6、
ng-dirty: 控制器与之有互动7、
ng-touched: 已经失去控制8、
ng-untouched: 还未失去控制9、
ng-pending: 异步验证($asyncValidators)还未结束
下面的示例使用CSS来显示每个表单控件的有效性。例子中,user.name 和 user.email 是必须的,当失去焦点时,会进行验证,如果验证不通过,那么背景色会变成红色的。这确保了用户不会忽略掉错误,知道验证通过了,才会同步到controller的model中去。
文件一:index.html
<div ng-controller="ExampleController">
<form novalidate class="css-form">
Name: <input type="text" ng-model="user.name" required /><br />
E-mail: <input type="email" ng-model="user.email" required /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="update(user)" value="Save" />
</form>
<pre>user = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<style type="text/css">
.css-form input.ng-invalid.ng-touched {
background-color: #FA787E;
}
.css-form input.ng-valid.ng-touched {
background-color: #78FA89;
}
</style>
<script>
angular.module(‘formExample‘, [])
.controller(‘ExampleController‘, [‘$scope‘, function($scope) {
$scope.master = {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}]);
</script>
标签:
原文地址:http://www.cnblogs.com/leosx/p/4911784.html