【发布时间】:2026-01-07 06:50:01
【问题描述】:
我编写了一个指令,可以为元素动态创建弹出框:
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()
});
}
};
});
在应用程序中它看起来像这样:
<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 在任何迭代中都会应用多次:
如您所见,应该只包含 3 个元素的迭代实际上包含 3*3 个元素。该指令为恰好 3 个元素创建弹出框,所以我想这就是我的错误所在。如何确保在每个弹出框内,ng-repeat 只被调用一次?
【问题讨论】:
-
尝试将代码放在编译块中
-
@Whisher 你能详细说明一下吗?我想将弹出框内容保留在主模板中。
-
在指令中而不是将代码放入链接块中尝试将其放入编译块中,以便代码编译一次。我快速查看您的代码,所以......我可以错误^^顺便说一句我不明白的另一件事是你为什么使用 $digest 不需要更新范围
-
@Whisher 但是我可以访问编译函数中的指令元素吗?
标签: javascript angularjs angularjs-directive angularjs-ng-repeat ng-repeat