AngularJS-如何在表单内部编译输入? [英] AngularJS - How to compile inputs inside form?

查看:111
本文介绍了AngularJS-如何在表单内部编译输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在html文件中声明的表单.输入是动态生成的.

I have a form declared in the html file. The inputs are generated dynamically.

这意味着,它们在javascript中作为字符串构建,然后在angular的自定义指令中编译.

That means, they are built as strings in javascript and then compiled inside a custom directive in angular.

app.directive('customInput', function($compile){
return{
  restrict: 'E',
  scope: true,
  link: function(scope, element, attrs){
    var html = "<input type='text' ng-model='tCtrl.test[$index]' ng-required='required' ng-maxlength='3'/>";
    var el = $compile(html)(scope);
    element.html("");
    element.append(el);
  }
}
});

它们可以与我的棱角代码一起正常工作,但是问题是:作为表单的一部分,它们没有被识别".也就是说,修改输入后,父FORM元素不会更改其$ pristine,$ error等状态.

They work fine with my angular code, but the problem is: They are not "recognized" as part of my form. That means, the parent FORM element does not change it's $pristine, $error, etc, status when inputs are modified.

如何将已编译的输入作为表单的一部分处理?

How can I have the compiled inputs be treated as part of the form?

这个笨拙的人就是我遇到的问题的一个例子:

This plunkr is an example of the problem I'm having:

http://plnkr.co/edit/tR7loK45wXEFcBIsDeur?p=preview

推荐答案

您正在做的是在将元素编译后放入dom,因此ngmodel没有机会将其自身连接到父表单.

what you are doing is putting the element on dom after compiling it, and hence the ngmodel does not get a chance to hookup itself to the parent form.

您正在做的是:

1. create & compile element
2. place it in dom

as元素在进入dom之前已经被编译.它永远不会知道其父形式,因此不会将自身链接到父.

as element is already compiled before making it to the dom.. it would never know of its parent form and hence wont link itself to the parent.

步骤顺序应为:

1. create an element, 
2. place it in dom 
3. compile it. // now it will have a chance to hook up to the parent

所以您宁愿做的是:

   var el =angular.element('your html');
   element.append(el);
   $compile(el)(scope);

这篇关于AngularJS-如何在表单内部编译输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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