1.入门
<form ng-controller="validationController" name="form1" novalidate>
<p> <input type="submit" ng-disabled="form1.$invalid">
<input type="email" name="myemail" ng-model="email" ng-minlength="10" ng-maxlength="50" required>
// 使用了 ng-show指令, color:red 在邮件是 $dirty 或 $invalid 才显示。
<span style="color:red" ng-show="form1.myemail.$dirty && form1.myemail.$invalid">
</span>
</p>
</form>
2.使用angular-messages
<!DOCTYPE html><html>
<head>
<title>Form</title>
<script type=‘text/javascript‘ src=‘http://cdn.bootcss.com/angular.js/1.4.9/angular.js‘></script>
<script type=‘text/javascript‘ src=‘http://cdn.bootcss.com/angular.js/1.4.9/angular-messages.js‘></script>
<style type="text/css">
.form1 {
transition:all linear 0.5s;
background: transparent;
}
</style>
</head>
<body ng-app="a8_8">
<form name="form1" ng-controller="form1Controller" class="form1" novalidate> <label ng-show="user.id != undefined" ng-model="user.id">
user id:<span>{{user.id}}</span>
</label><br>
<label>Enter text: <input type="email" ng-model="email1" name="myemail" required ng-minlength="10" maxlength="15" /> </label>
<div style="color:red" ng-messages="form1.myemail.$error" ng-messages-multiple role="alert" ng-if="form1.myemail.$touched">
<div ng-message="required">Email is required.</div>
<div ng-message="email">Invalid email address.</div>
<div ng-message="minlength">min length 10.</div>
<div ng-message="maxlength">max length 50.</div>
</div> <p> <input type="submit" value="提交" ng-disabled="form1.$invalid" /></p>
<span class="error" ng-show="form1.myemail.$error.required">Required!</span><br>
<code>form1.myemail.$valid = {{form1.myemail.$valid}}</code><br>
<code>form1.myemail.$error = {{form1.myemail.$error}}</code><br>
<code>form1.$valid = {{form1.$valid}}</code><br>
<code>form1.$error.required = {{!!form1.$error.required}}</code><br>
<button ng-click="reset()" ng-disabled="isUnchanged(user)">RESET</button>
<button ng-click="update(user)" ng-disabled="form1.$invalid || isUnchanged(user)">SAVE</button> <br>
</body>
</html>
3.数据提交
已经不用传统的submit,是基于model 的后台处理<script type="text/javascript">
var app = angular.module(‘a8_8‘, [‘ngMessages‘]);
app.controller(‘form1Controller‘, [‘$scope‘,function($scope) {
$scope.user = {email:‘[email protected]‘};
$scope.master = {email:‘[email protected]‘};
$scope.update = function(user) {
$scope.master = angular.copy(user);
console.log( ‘save‘+user);
user.id=1;
console.log( user);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.isUnchanged = function(user) {
return angular.equals(user, $scope.master);
};
}]);
</script>
时间: 2024-11-02 08:19:58