我希望将带有 $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/