简体   繁体   English

AngularJS:将数据绑定到动态创建的HTML

[英]AngularJS: Binding Data to Dynamically Created HTML

I have a script that dynamically creates HTML form fields. 我有一个可以动态创建HTML表单字段的脚本。 I am trying to use Angular directives to bind data. 我正在尝试使用Angular指令来绑定数据。 I believe the binding is not occurring because the HTML elements are not there on page load since they are being dynamically created. 我相信不会发生绑定,因为HTML元素是动态创建的,因此页面加载时就没有HTML元素。 Here is my HTML: 这是我的HTML:

<div id="form-builder-wrapper">
      <form class="form-horizontal" role="form" autocomplete="off">
          <ul class="handles">
              <br />
              <!--Dynamic HTML is being appended here with jQuery-->
          </ul>
          <button class="btn btn-primary m-t-20 hide" type="submit">Submit</button>
      </form>
</div>

My jQuery is dynamically appending my HTML elements in the form above. 我的jQuery正在以上述形式动态附加我的HTML元素。 Here is a sample element that is being appended: 这是一个附加的示例元素:

<div class="form-group requiredField" id="element_1" data-type="textbox">
    <label for="element_label_1" class="col-sm-3 control-label" ng-bind="element_label_1">First Name</label>
    <div class="col-sm-9">
        <input type="text" class="form-control" name="element_1" id="element_label_1" required="">
    </div>
</div>

As you can see, in my label field, I am attaching a ng-bind="element_label_1" directive. 如您所见,在我的label字段中,我附加了ng-bind="element_label_1"指令。 I am attempting to update the label with this code: 我正在尝试使用以下代码更新label

<p>Update Label: <input type="text" ng-model="element_label_1"></p>

But this is not working. 但这是行不通的。 It is not binding together. 它没有绑定在一起。 Any idea of what I am doing wrong? 任何我做错事的想法吗?

If you're adding to the DOM tree after DOM load, you've likely missed the compilation/linking process that Angular does. 如果要在DOM加载后添加到DOM树中,则可能错过了Angular进行的编译/链接过程。 You'll have to manually compile and link your new elements using the $compile service. 您必须使用$ compile服务手动编译和链接新元素。

 parent.append(element);
 $compile(element)($scope);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM