javascript - AngularJS $compiled 元素不会添加到它们所在的表单中。

标签 javascript angularjs forms

我希望将带有 $compiled 到模板上的表单属性的元素字符串直接添加到它们编译到的表单中(通过 DOM 继承),但从测试来看,事实并非如此自动发生。如果发生这种情况就好了,这样我就可以验证表单,包括新编译的具有表单属性的元素。

JS

.directive('addDynamicFormElements', ['$compile', function($compile) {
  return {
    link: function (scope, elem, attrs) {
      var tmpl = "<input name='newFormItem' ng-model='formScope.item3' required>";
      scope.click = function () {
        var el = angular.element(document.querySelector('#addFieldHere'));
        var compiled = $compile(tmpl)(scope);
        el.append(compiled);
      }
    }
  }
}]);

HTML

<h1>My Form</h1>
 <div ng-form="myForm">
    <input name="first" ng-model="formScope.item1">
    <input name="second" ng-model="formScope.item2">
    <button add-dynamic-form-elements ng-click="click()">Click here to append a new field</button>
    <div id="addFieldHere"></div>
 </div>

这是一个PLNKR,通过将表单表达式绑定(bind)到模板,可以清楚地看到表单并不直接包含新编译的元素:http://plnkr.co/edit/Blogc4lSVyNd26ySwGlq?p=preview

感谢您的帮助!

最佳答案

正如您所知,$compile 返回一个链接函数。该链接函数返回已经链接的元素。该元素尚未放入 DOM 中,因此在链接阶段它不知道它应该采用的形式。

解决这个问题的两种方法:

#1:使用cloneAttachFn函数:

link: function(scope, element){

  var tmpl = "<input name='newFormItem' ng-model='formScope.item3' required>";

  $compile(tmpl)(scope, function cloneAttachFn(prelinkedClone){
    element.append(prelinkedClone);
  });
}

#2:在编译/链接之前将元素附加到 DOM:

link: function(scope, element){

  var tmpl = "<input name='newFormItem' ng-model='formScope.item3' required>";
  var templateElement = angular.element(tmpl);

  element.append(templateElement);
  $compile(templateElement)(scope);
}

关于javascript - AngularJS $compiled 元素不会添加到它们所在的表单中。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31844216/

相关文章:

javascript - '类型错误: undefined is not a function' when pulling json data from the github api in Angular?

javascript - Twitter Bootstrap 模态通过 Ajax 更改内容

javascript - 如何动态地将 Angular 变量的值设置为另一个变量

PHP Form 将空白行写入 MySQL DB

javascript - 提交成功后如何让数据消失

forms - 使用表单更新谷歌电子表格上的现有数据?

javascript - 如何在fabric js中实现橡皮擦

javascript - 在指令中使用 $watch 进行了一个小实验

javascript - Angular JS : Javascript not working inside custom directive template

Javascript 搜索不按顺序排列的单词