AngularJS ng-repeat在$ compiled指令中多次应用 [英] AngularJS ng-repeat applied multiple times in $compiled directive
问题描述
我写了一条指令,可以为元素动态创建弹出框:
I've written a directive that dynamically creates a popover for an element:
app.directive('popover', function($compile, $timeout){
return {
link: function(scope, element, attrs) {
$timeout(function() {
// grab template
var tpl = $(element).find('.popover-template')
// grab popover parts of template
var template = {
//$compile( $(element).siblings(".pop-content").contents() )(scope)
title: tpl.find('.template-title').contents(),
content: tpl.find('.template-content').contents()
};
// render template with angular
var content = $compile(template.content)(scope);
var title = $compile(template.title)(scope);
$(element).popover({
html: true,
placement: "right",
content: content,
title: title
});
scope.$digest()
});
}
};
});
在应用程序中,它看起来像这样:
In application it looks like this:
<span popover>Click me</span>
<div ng-hide="true" class="popover-template">
<div class="template-title">
<strong>{{ x.name }} and {{ y.name }}</strong>
</div>
<div class="template-content">
<div>
<pre>f in [1,2,3]</pre>
<div ng-repeat="f in [1,2,3]">
item {{ f }}, index {{ $index }}
</div>
</div>
</div>
</div>
将创建并显示弹出窗口.标题也可以正常工作.但是, ng-repeat 在任何迭代中都会多次应用:
The popover is created and displayed. The title works correctly as well. However, ng-repeat is applied multiple times in any iteration:
如您所见,实际上只应包含3个元素的迭代实际上包含3 * 3个元素.该指令为3个元素创建弹出窗口,所以我猜这就是我的错误所在.如何确保在每个弹出窗口中,ng-repeat
仅被调用一次?
As you can see, the iteration that should only include 3 elements in fact includes 3*3 elements. The directive creates popovers for exactly 3 elements, so I guess that's where my mistake lies. How can I make sure that within each popover, ng-repeat
is only called once?
推荐答案
问题
由于自举角度应用程序时(页面加载时)popover-template元素已存在于文档中,因此它已经被编译一次. ng-repeat元素替换为3个新元素:
The problem
Since the popover-template element is already in the document when you bootstrapped the angular application (at page load), it has already been compiled once. The ng-repeat element is replaced with 3 new elements:
<!-- original -->
<div ng-repeat="f in [1,2,3]">item {{ f }}, index {{ $index }}</div>
<!-- replaced -->
<div ng-repeat="f in [1,2,3]">item 1, index 0</div>
<div ng-repeat="f in [1,2,3]">item 2, index 1</div>
<div ng-repeat="f in [1,2,3]">item 3, index 2</div>
在链接功能中再次对其进行编译时,将触发3个ng重复中的每一个,产生3个相同的副本,共9个.
When you compile it again in the link function, each of the 3 ng-repeats is triggered, making 3 identical copies, 9 total.
将弹出模板保留在单独的文件中,这样它不会在页面加载时进行编译.然后,您可以使用 $ templateCache 服务加载它.
Keep your popover-template in a separate file so it is not compiled on page load. You can then load it with the $templateCache service.
通常,只需确保不要多次编译HTML.
In general, just make sure you don't compile your HTML multiple times.
这篇关于AngularJS ng-repeat在$ compiled指令中多次应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!