来自 angular 指令的新添加元素未编译 [英] Newly added elements from angular directive not getting compiled
问题描述
我按照要求用一些 div
标签包裹了我的 input
标签.现在的问题是,div
标签的类正在按角度动态变化,但似乎这个新添加的 div
没有被编译,因此,它显示在页面上(在浏览器中查看源代码)与我添加的完全一样.如果我直接在页面上而不是从指令中添加它,通常不会发生任何变化.
I wrapped my input
tag with some div
tags as per the requirement. Now the issue is, class of div
tag is changing dynamically by angular, but seems this newly added div
is not getting compiled and because of that, it is shown on the page (saw in view source in browser) exactly as I add it. No change is happening which it usually does if I add it directly on page instead of from directive.
我也尝试在这个 div
中添加 {{ name }}
但它也没有打印 name 属性,而直接在页面上添加它,确实有效.这给了我新添加的 div
没有得到正确编译的结论.
I tried adding {{ name }}
also in this div
but it also doesn't print the name property while adding it directly on page, does work. This gave me the conclusion that the newly added div
is not getting compiled properly.
我是这样从 html 调用的,
I'm calling from html like this,
<!-- ag-textbox is my directive -->
<input ag-textbox ag-grid-class="col-md-4" class="form-control" id="age" type="text" ag-name="Age" ng-model="age" ag-formname="newform" required />
我在 js 中的代码是,
My code in js is,
var fDiv = angular.element("<div class='" + agGridClass + "' "
+ "ng-class={'has-error':" + agFormName + "." + agName + ".$invalid}>");
element.wrap(fDiv);
$compile(element.contents())(scope);
当我不使用 wrap()
函数时它正在工作,如下所示:
It was working when I wasn't using wrap()
function as below:
element.html('').append(firstDiv + inputText + otherDiv);
$compile(element.contents())(scope);
这工作正常,但现在我的要求不同了,我必须包装现有的 input
标签,因此必须使用 wrap()
函数.
This was working fine but now my requirement is different and I have to wrap the existing input
tag so have to use the wrap()
function.
我已经尝试过 $compile(element)(scope)
和 $compile(element.html())(scope)
但它们都不能正常工作.有没有办法编译新添加的组件?
I have tried $compile(element)(scope)
and $compile(element.html())(scope)
but none of them work as well. Is there any way to compile the newly added components?
推荐答案
调用 .wrap()
后,element
仍然是对原始 DOM 元素的引用,即不包括它被包裹的 div.所以当你编译 element
时,被包裹的 div 不会被编译.
After calling .wrap()
, element
is still a reference to the original DOM element, which doesn't include div that it is wrapped in. So when you compile element
, the wrapped div is not compiled.
假设 fDiv
是一个简单的 div,您可以尝试使用 .parent()
将其包含在编译中...
Assuming fDiv
is a simple div, you can try using .parent()
to include it in the compilation...
element.wrap(fDiv);
$compile(element.parent().contents())(scope);
编辑...
fDiv 似乎在 ng-class 属性中缺少 "
s,需要关闭 </div>
标记...
fDiv appears to be missing "
s in the ng-class attribute and needs a closing </div>
tag...
var fDiv = angular.element("<div class='" + agGridClass + "' "
+ "ng-class=\"{'has-error':" + agFormName + "." + agName + ".$invalid}\"></div>");
这篇关于来自 angular 指令的新添加元素未编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!