自定义验证
ctrl.$setValidity(‘field’,true/false)
ngMessages用于简化验证提示信息代码的编写
1.导入angular-messages.js
2.添加依赖‘ngMessages’
3.设置ng-messages=”form.name.$error”
4.设置ng-message=”required”
通过验证用户名的唯一性:
app.directive('ensureUnique', function () {
return {
require:'ngModel',
link: function (scope, element, attrs, ctrl) {
console.log(attrs.ngModel);
//通过检测属性ngModel的名称的变化,动态查询是否存在相应的用户名
scope.$watch(attrs.ngModel, function (newVal,oldVal) {
if(['Tom','Jerry'].indexOf(newVal) != -1){ //新注册的用户名在其中
ctrl.$setValidity('unique',false);
}
else{
ctrl.$setValidity('unique',true);
}
})
}
}
})
<form name="myForm" ng-submit="submit()" novalidate>
<input type="text" ng-model="username" name="username" ng-minlength="5" ng-maxlength="15" required ensure-unique />
<div class="invalid" ng-messages="myForm.username.$error" ng-messages-include="error-messages.html">
</div>
<input type="submit"/>
</form>