nor*_*ght 15 html javascript validation angularjs ng-messages
我在angularjs中编写Web应用程序并使用角度材料(不确定这是否与问题相关)和ngMessages为用户提供无效输入的反馈.
通常,为了验证所提供的指令,我可以通过类似于以下的方式进行验证:
<md-input-container>
<input required name="myInput" ng-model="someModel">
<div ng-messages="formName.myInput.$error">
<div ng-message="required">This field is required.</div>
</div>
</md-input-container>
Run Code Online (Sandbox Code Playgroud)
但是如果我创建了自己的自定义指令......
moduleName.directive('ngCustomdir', function(){
return {
restrict: 'A',
require: 'ngModel',
link: function($scope, $element, $attrs, ngModel){
//do some validation
return validation; //<--true or false based on validation
}
};
}
Run Code Online (Sandbox Code Playgroud)
并将其包含在我的输入中......
<input required ng-customdir name="myInput" ng-model="someModel">
Run Code Online (Sandbox Code Playgroud)
我知道它会验证输入,因为如果根据我的自定义指令验证输入无效,则字段变为红色且$ invalid值设置为true,但我不知道如何根据何时使用ngMessages显示消息有时候是这样的.
<div ng-messages="formName.myInput.$error">
<div ng-message="required">This field is required.</div>
<div ng-message="customdir">This is what I need to appear.</div>
</div>
Run Code Online (Sandbox Code Playgroud)
当我的自定义指令验证无效时,我似乎无法显示消息.我该怎么做呢?我在这里先向您的帮助表示感谢.
Huy*_*ham 21
你变得非常接近,只需在你的link函数中添加一些验证:
link: function($scope, $element, $attrs, ngModel){
ngModel.$validators.required = function(modelValue) {
//true or false based on required validation
};
ngModel.$validators.customdir= function(modelValue) {
//true or false based on custome dir validation
};
}
Run Code Online (Sandbox Code Playgroud)
当模型更改时,AngularJS将调用$validatorsobject中的所有验证函数.ng-message将根据功能名称显示.有关$ validators的更多信息:
https://docs.angularjs.org/api/ng/type/ngModel.NgModelController
http://blog.thoughtram.io/angularjs/2015/01/11/exploring-angular-1.3-validators-pipeline.html
| 归档时间: |
|
| 查看次数: |
11868 次 |
| 最近记录: |