<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="angular.js"></script>
<script src="angular-messages.js"></script>
<script>
angular.module("app", ["ngMessages"])
.directive("ensureUnique", function($http) {
return {
require: "?^ngModel",
//原文中混用了ngModel和ctrl,这里统一使用ngModel,意指ngModelController
link: function(scope, element, attrs, ngModel) {
var url = attrs.ensureUnique;
if (!ngModel) {
return false;
}
ngModel.$parsers.push(function(val) {
if (!val || val.length == 0) {
return false;
}
//设置表单状态,属性统一归于signup_form.username.$error中,这是为设置是否合法状态,所以如果设置为false,则会在ng-messages中显示,因为它调用的是$error方法,意为是否“不合法”,原文有错误。
ngModel.$setValidity("checkingAvailability", false);
ngModel.$setValidity("usernameAvailability", true);
$http({
method: "POST",
url: url,
data: {
username: val
}
}).then(function(r) {
if ("exist" == r.data) {
ngModel.$setValidity("checkingAvailability", true);
ngModel.$setValidity("usernameAvailability", false);
} else {
ngModel.$setValidity("checkingAvailability", true);
ngModel.$setValidity("usernameAvailability", true);
}
}, function(e) {
console.log(e);
})
return val;
})
}
}
})
.controller("MainController", function($scope) {
$scope.signup = {
username: ""
}
})
</script>
</head>
<body>
<div ng-controller="MainController">
<form name="signup_form" novalidate ng-submit="signupForm()">
<!-- 原文中指令放在了form元素中,应该放在input元素中 -->
<input type="text" name="username" ng-model="signup.username" required ng-min-length=3 ng-max-length=10 ensure-unique="check.php">
<!-- 输入过才显示操作信息 -->
<div class="error" ng-show="signup_form.$dirty" ng-messages="signup_form.username.$error" ng-messages-multiple>
<div ng-message="required">
Required!!!
</div>
<div ng-message="checkingAvailability">
Checking...
</div>
<div ng-message="usernameAvailability">
Has been taken, please choose another.
</div>
</div>
<div>
<button type="submit">Submit</button>
</div>
<p>{{signup_form.username.$error}}</p>
</form>
</div>
</body>
</html>
<?php
//Angular与jQuery传递参数类型不同,不能直接使用$.POST['username']获取;
$postData = file_get_contents('php://input', true);
$obj=json_decode($postData);
//这里模拟唯一性验证
if($obj->username == '123'){
echo "exist";
}
else{
echo "available";
}
?>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有