使用每次都不同的 transclude 重复指令
Repeating a directive with transclude that is different each time
在我的 angular 应用程序中,我有几个具有相同结构的共享面板 html。
面板内部的内容和行为发生变化,基本上每一个都是一个单独的指令,我们称它们为面板内容。
这是我认为最接近的解决方案,但我对架构有一些疑问。
因为我有指令(其中包含 true 集):
<panel></panel>
它的模板如下所示:
<div>
Content
<ng-transclude></ng-transclude>
</div>
我必须重复面板
<ul>
<li ng-repeat="panel in panels">
<panel>
<panel-content></panel-content>
</panel>
</li>
</ul
这一切都很好,但是在我应该显示 <panel-content>
的每次迭代中 "choosing" 的合理好方法是什么?
假设我有一个 panel.id
我可以使用。
我注意到我可以通过多种方式实现它,我可以使用面板 ID 在 <panel-content>
视图中执行 ng-switch,我可以设置 templateUrl 具有动态部分并链接到不同的 URL 取决于 panel.id
.
但出于某种原因,我确信我错过了一些更好更直接的东西?
请注意,此架构并非一成不变,如果有其他架构更适合我的需求,请告诉我。
那么,问题又来了,我该如何选择呢?或者更确切地说,谁负责选择应该显示哪个 <panel-content>
。
如果我没理解错的话,我会在指令中使用 ng-include
,每次通过 id
:
更改模板
类似于:
<ul>
<li ng-repeat="panel in panels">
<panel type-id="panel.id">
</panel>
</li>
</ul>
和指令:
app.directive('panel',
function() {
return {
restrict: 'E',
replace: true,
template: '<ng-include src="getTemplateUrl()"/>',
link: function(scope,elem,attrs) {
scope.getTemplateUrl = function() {
var url;
if(attrs.typeId !== undefined){
var url = $rootScope.list_templates[attrs.typeId].value; // TODO: add validation
}
return url;
};
}
});
应用程序
$rootScope.list_templates = [
{ id: 0, value: 'partials/upcoming_0.html'},
{ id: 1, value: 'partials/upcoming_1.html'},
{ id: 2, value: 'partials/upcoming_2.html'}
];
在我的 angular 应用程序中,我有几个具有相同结构的共享面板 html。
面板内部的内容和行为发生变化,基本上每一个都是一个单独的指令,我们称它们为面板内容。
这是我认为最接近的解决方案,但我对架构有一些疑问。
因为我有指令(其中包含 true 集):
<panel></panel>
它的模板如下所示:
<div>
Content
<ng-transclude></ng-transclude>
</div>
我必须重复面板
<ul>
<li ng-repeat="panel in panels">
<panel>
<panel-content></panel-content>
</panel>
</li>
</ul
这一切都很好,但是在我应该显示 <panel-content>
的每次迭代中 "choosing" 的合理好方法是什么?
假设我有一个 panel.id
我可以使用。
我注意到我可以通过多种方式实现它,我可以使用面板 ID 在 <panel-content>
视图中执行 ng-switch,我可以设置 templateUrl 具有动态部分并链接到不同的 URL 取决于 panel.id
.
但出于某种原因,我确信我错过了一些更好更直接的东西?
请注意,此架构并非一成不变,如果有其他架构更适合我的需求,请告诉我。
那么,问题又来了,我该如何选择呢?或者更确切地说,谁负责选择应该显示哪个 <panel-content>
。
如果我没理解错的话,我会在指令中使用 ng-include
,每次通过 id
:
类似于:
<ul>
<li ng-repeat="panel in panels">
<panel type-id="panel.id">
</panel>
</li>
</ul>
和指令:
app.directive('panel',
function() {
return {
restrict: 'E',
replace: true,
template: '<ng-include src="getTemplateUrl()"/>',
link: function(scope,elem,attrs) {
scope.getTemplateUrl = function() {
var url;
if(attrs.typeId !== undefined){
var url = $rootScope.list_templates[attrs.typeId].value; // TODO: add validation
}
return url;
};
}
});
应用程序
$rootScope.list_templates = [
{ id: 0, value: 'partials/upcoming_0.html'},
{ id: 1, value: 'partials/upcoming_1.html'},
{ id: 2, value: 'partials/upcoming_2.html'}
];