AngularJs:如何对指令创建的动态元素应用Form验证

AngularJs: how to apply Form validation on dynamic element created by directive

本文关键字:元素 动态 应用 Form 验证 创建 指令 AngularJs      更新时间:2023-09-26

在我们的表单中,元素是使用ng repeat动态创建的。将表单值存储在$scope.answers.[attribute name]中。

以同样的方式,我想在表单提交时对更改进行验证。但无法调用对动态元素的验证。

我的html元素(index.html)

<div ng-if="que.QuestionData._fieldType === 'text'" >
                        <text-control-dir data-que-obj="que.QuestionData" ></text-control-dir>  
                        {{answers[que.QuestionData._attributeName]}}
                        <span ng-show="DTOstep1.answers[que.QuestionData._attributeName].$touched && DTOstep1.answers[que.QuestionData._attributeName].$invalid">The name is required.</span>
                    </div>  

(controlDirective.js)指令具有用于表单控件的html。有关完整代码,请参阅此plunker。https://plnkr.co/edit/GA74YHNFxFb0ARg16Sjj?p=preview

首先需要使用ngModelhttps://docs.angularjs.org/api/ng/directive/ngModel.否则,它不会在您的表单中注册任何验证错误。此外,您不需要elemen.on('change'),只需使用ngModel指令。最后,如果您使用自己的验证消息,请将novalidate属性添加到表单元素中。

ngModel负责:

  • 将视图绑定到模型中,text区域或选择require。

  • 提供验证行为(即。必填,数字,电子邮件,网址)。

  • 保持控件的状态(有效/无效、脏/原始、触摸/未触摸、验证错误)。

  • 在元素上设置相关的css类(ng valid,ng肮脏,ng质朴,ng感动,ng未动,ng空虚,ng不为空),包括动画。

  • 将控件注册到父窗体.

顺便说一句,前缀为ng-的指令不需要{{ }}。例如,你不应该写

required="{{queObj._required}}"required="queObj._required"

这是一个用于文本控制目录的工作plunker

https://plnkr.co/edit/wDPtvj29pt0E6Y7QC0j0?p=preview