AngularJS动态表单字段验证 [英] AngularJS dynamic form field validation

查看:340
本文介绍了AngularJS动态表单字段验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证这是给我从后端端点某种形式的领域...

I am trying to validate some form fields which are given to me from a backend endpoint...

所以基本上输入元素动态地 NG-重复内创建
因此,输入属性也被动态添加,如键入名称,等...

So basically the input elements are dynamically created inside a ng-repeat. Therefore, the input attributes are also dynamically added, such as the type, name, etc...

不过因为名称属性动态添加,当我尝试验证它,像这样的,例如:

However because the name attribute is dynamically added, when I try to validate it, like this, for example:

myForm.elName.$valid

这并不因为此时返回任何东西,它不知道是什么 elName

我创建了一个的jsfiddle来说明问题:
http://jsfiddle.net/peduarte/HB7LU/1889/

I created a jsFiddle to demonstrate the problem: http://jsfiddle.net/peduarte/HB7LU/1889/

任何帮助或建议将大大AP preciated!

Any help or advice will be much appreciated!

FANX。

编辑:结果
我已经提到这个真棒文档:
<一href=\"http://docs.angularjs.org/api/ng.directive:input.email\">http://docs.angularjs.org/api/ng.directive:input.email

推荐答案

尝试我的自定义指令:

myApp.directive("dynamicName",function($compile){
  return {
      restrict:"A",
      terminal:true,
      priority:1000,
      link:function(scope,element,attrs){
          element.attr('name', scope.$eval(attrs.dynamicName));
          element.removeAttr("dynamic-name");
          $compile(element)(scope);
      }
   };
});

使用它:

<input dynamic-name="field.name"
       type="{{ field.type }}"
       placeholder="{{ field.name }}"
       ng-model="field.value"
       required>

演示

问题的说明:

在默认情况下,使用ngModelController( NG-模型)调用的FormController。$的AddControl input元素,当它们被链接自我注册并在的FormController 通过输入是 name属性{{field.name公开财产}} 在这种情况下。因此,即使该控件注册,但你没有暴露与名为电子邮件上的FormController 属性的firstName ,你只有 {{} field.name} 引用的最后一个输入项

By default, input elements using ngModelController (ng-model) call FormController.$addControl when they are linked to register itself and expose a property on the FormController with the name property of the input which is {{ field.name }} in this case. Therefore, even though the control is registered but you don't have exposed properties on FormController with named email, firstName, you only have {{ field.name }} referencing the last input item

解决方案的说明:

在这个解决方案,我创建了一个自定义的指令来替换 {{} field.name} 在运行时的正确名称。

In this solution, I created a custom directive to replace the {{ field.name }} with the correct name at runtime.

有关我为什么要使用终端信息真实,优先级:1000 ,看看这个讨论:<一href=\"http://stackoverflow.com/questions/19224028/add-directives-from-directive-in-angularjs/19228302#19228302\">Add在AngularJS

For more information why I have to use terminal:true, and priority:1000, check out this discussion: Add directives from directive in AngularJS

这篇关于AngularJS动态表单字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆