gpt4 book ai didi

javascript - 将模型传递给自定义 Angular Directive(指令)进行验证

转载 作者:行者123 更新时间:2023-12-03 09:29:42 25 4
gpt4 key购买 nike

我创建了一个小的 angularjs 指令来在我的页面上显示验证错误

这是代码

.directive('validationErrors', function() {
return {
templateUrl: '/Content/biz/templates/common/validation-errors.html',
replace: true,
restrict: 'E',
scope: {
modelToValidate: '=',
modelMinLength: '=',
modelMaxLength: '=',
modelPattern: '='
}
}
});

以及它的模板

<div class="col-sm-5 pull-right" data-ng-show="modelToValidate.$dirty && modelToValidate.$invalid">
<span class="label label-warning" data-ng-show="modelToValidate.$error.required">This field is required!</span>
<span class="label label-warning" data-ng-show="modelToValidate.$error.minlength">Minimum field length should be {{modelMinLength}}</span>
<span class="label label-warning" data-ng-show="modelToValidate.$error.maxlength">Maximum field length should be {{modelMaxLength}}</span>
<span class="label label-warning" data-ng-show="modelToValidate.$error.pattern">Model should have {{modelPattern}}</span>

然后我将它绑定(bind)到模型

 <div class="col-sm-4">
<input class="form-control" ng-model="data.Main.FullName" ng-maxlength="1000" required/>

这会生成像这样的标记

<div class="col-sm-4">
<input class="form-control ng-valid-maxlength ng-dirty ng-valid-parse ng-invalid ng-invalid-required ng-touched" ng-model="data.Main.FullName" ng-maxlength="1000" required="">
<div class="col-sm-5 pull-right ng-isolate-scope" model-to-validate="data.Main.FullName" model-max-length="1000">
<span class="label label-warning ng-hide" data-ng-show="modelToValidate.$error.required">This field is required!</span>
<span class="label label-warning ng-binding ng-hide" data-ng-show="modelToValidate.$error.minlength">Minimum field length should be </span>
<span class="label label-warning ng-binding ng-hide" data-ng-show="modelToValidate.$error.maxlength">Maximum field length should be 1000</span>
<span class="label label-warning ng-binding ng-hide" data-ng-show="modelToValidate.$error.pattern">Model should have </span>

但是如果绑定(bind)模型有错误,则不会显示任何内容。请帮助我理解为什么会这样。

最佳答案

我认为您需要传递给您的表单是一个 ngModelController实例,而您传递的是模型实例。

首先将输入更改为具有名称属性

<input name="fullName" class="form-control" ng-model="data.Main.FullName" ng-maxlength="1000" required/>
(还要确保您的表单具有名称属性,我们假设它是 myForm )

然后指令参数应该是

<div model-to-validate="myForm.FullName" model-max-length="1000">

现在应该可以了。记住您正在使用的所有属性,例如 $error是在 NgModelController 实例上定义的,而不是在模型上定义的。

您正在做的事情也可以在 Angular 1.4 中使用 ngMessage 来完成

关于javascript - 将模型传递给自定义 Angular Directive(指令)进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31553878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com