这篇文章主要为大家详细介绍了基于angularjs实现表单验证功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了angularjs实现表单验证功能的具体代码,供大家参考,具体内容如下
<!--实例解析
ng-app 指令定义了 angularjs 应用。
ng-controller 指令定义了应用控制器。
ng-model 指令绑定了两个 input 元素到模型的 user 对象。
formctrl 函数设置了 master 对象的初始值,并定义了 reset() 方法。
reset() 方法设置了 user 对象等于 master 对象。
ng-click 指令调用了 reset() 方法,且在点击按钮时调用。
novalidate 属性在应用中不是必须的,但是你需要在 angularjs 表单中使用,用于重写标准的 html5 验证。 -->
<!doctype html>
<html ng-app="myapp">
<head>
<meta charset="utf-8">
<script src="js/angular.js"></script>
</head>
<body>
<!-- checkbox(单选框)
我们可以使用 ng-model 来绑定单选按钮到你的应用中。
单选框使用同一个 ng-model ,可以有不同的值,但只有被选中的单选按钮的值会被使用
-->
<form>
选择一个选项:
<input type="radio" ng-model="myvar" value="dogs">dogs
<input type="radio" ng-model="myvar" value="tuts">tutorials
<input type="radio" ng-model="myvar" value="cars">cars
</form>
<p ng-switch="myvar">
<p ng-switch-when="dogs">
<h1>dogs</h1>
<p>welcome to a world of dogs.</p>
</p>
<p ng-switch-when="tuts">
<h1>tutorials</h1>
<p>learn from examples.</p>
</p>
<p ng-switch-when="cars">
<h1>cars</h1>
<p>read about cars.</p>
</p>
</p>
<p>ng-switch 指令根据单选按钮的选择结果显示或隐藏 html 区域。</p><br><br><br><br>
<!-- 下拉菜单
使用 ng-model 指令可以将下拉菜单绑定到你的应用中。
ng-model 属性的值为你在下拉菜单选中的选项
-->
<form>
选择一个选项:
<select ng-model="myvar2">
<option value="">
<option value="dogs">dogs
<option value="tuts">tutorials
<option value="cars">cars
</select>
</form>
<p ng-switch="myvar2">
<p ng-switch-when="dogs">
<h1>dogs</h1>
<p>welcome to a world of dogs.</p>
</p>
<p ng-switch-when="tuts">
<h1>tutorials</h1>
<p>learn from examples.</p>
</p>
<p ng-switch-when="cars">
<h1>cars</h1>
<p>read about cars.</p>
</p>
</p>
<p>ng-switch 指令根据下拉菜单的选择结果显示或隐藏 html 区域。</p><br><br><br><br>
<!-- novalidate-->
<form action="xxx.do" novalidate>
e-mail: <input type="email" name="user_email">
<input type="submit">
</form>
<p><strong>注意:</strong>在 safari 和 internet explorer 9 及之前的版本中不支持 novalidate 属性。这个属性可以关闭浏览器默认校验</p><br><br><br><br>
<!--checkbox(复选框)
checkbox 的值为 true 或 false,可以使用 ng-model 指令绑定,它的值可以用于应用中-->
<p ng-app="">
<form>
选中复选框,显示标题:
<input type="checkbox" ng-model="myvar">
</form>
<h1 ng-show="myvar">my header</h1>
</p>
<p>标题使用了 ng-show 指令,复选框选中后显示 h1 标签内容。</p><br><br><br><br>
<!-- html 表单
html 表单通常与 html 控件同时存在
以下 html input 元素被称为 html 控件:
input 元素
select 元素
button 元素
textarea 元素
-->
<p ng-app="myapp" ng-controller="formctrl">
<form novalidate>
first name:<br>
<input type="text" ng-model="user.firstname"><br>
last name:<br>
<input type="text" ng-model="user.lastname">
<br><br>
<button ng-click="reset()">reset</button>
</form>
<p>form = {{user}}</p>
<p>master = {{master}}</p>
</p>
<script>
var app = angular.module('myapp', []);
app.controller('formctrl', function($scope) {
$scope.master = {firstname: "john", lastname: "doe"};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
});
</script>
</body>
</html>
以上就是利用angularjs完成表单验证功能的介绍的详细内容。