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

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

在我们的表单中,元素是使用 ng-repeat 动态创建的。 在 $scope.answers.[属性名称].

中存储表单值

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

我的 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>  

(controlDirectives.js) 指令有 html 用于表单控件。 请参阅此 plunker 以获取完整代码。 https://plnkr.co/edit/GA74YHNFxFb0ARg16Sjj?p=preview

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

ngModel is responsible for:

  • Binding the view into the model, which other directives such as input, textarea or select require.

  • Providing validation behavior (i.e. required, number, email, url).

  • Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).

  • Setting related css classes on the element (ng-valid, ng-invalid, ng-dirty, ng-pristine, ng-touched, ng-untouched, ng-empty, ng-not-empty) including animations.

  • Registering the control with its parent form.

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

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

这是 text-control-dir

的工作 plunker

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