如何使用角度将输入值不带输入控制器?

时间:2019-01-09 17:35:13

标签: javascript

这是一个有角度的项目,但是我有一种情况,我需要在不使用有角度的2向绑定的情况下将输入字段值输入到控制器中。

问题在于我的输入字段是通过以下代码动态添加到html中的:

       $( "#my-input-fields")
          .append( "<li style='height:15px;' >" + " Type the id. code here:" + 
                  "<input type='text' ng-model='c1.myVar' />" +   
                  "</li>" )
                  .css( "list-style-type", "none");

尽管已正确添加到html中,但是无论我在输入字段中键入什么内容,都永远不会在控制器上填充c1.myvar。换句话说,2向绑定不起作用。

在我使用jquery动态添加html变量后,是否有一种方法可以激活html变量的2向绑定?另外,我想知道是否存在另一种方法来接收用户在其中键入c1.myVar的值。

谢谢。

1 个答案:

答案 0 :(得分:0)

在将其附加到DOM之前,必须进行动态编译才能获得与$compile的绑定。这就是你的方法。

var element = "<li style='height:15px;' >" + " Type the id. code here:" + "<input type='text' ng-model='c1.myVar' />" + "</li>"

var compile = $compile(element)($scope);

现在您可以将其附加到元素或任何想要的地方

$( "#my-input-fields").append(compile )

不要忘记在控制器中注入$compile