gpt4 book ai didi

javascript - 在 Angular Directive(指令)中重复嵌入的内容

转载 作者:太空宇宙 更新时间:2023-11-04 16:27:38 24 4
gpt4 key购买 nike

我正在尝试在 Angular 中编写一个简单的树指令,它将嵌套项目,并在每个重复项目中重复第一次调用该指令时声明的嵌入内容。

我已经尝试过了,

angular.module('angularTree',[])
.directive('tree',['$compile',function($compile)
{

return {

scope:{item:"="},
transclude:true,
template:"<div class='tree-item'><ng-transclude></ng-transclude>" +
"<div id='tree-content' class='tree-content'>" +
"<div ng-repeat='child in item.items'>" +
"<tree item='child'><ng-transclude></ng-transclude></tree>" +
"</div>" +
"</div>",
link:function(scope,element,attrs)
{

}
}


}]);

在一定程度上它是有效的。它创建一个嵌套树,其中包含嵌入的内容。

问题在于重复子指令中的范围始终指向声明的第一个项目。所以当我的 Controller 中有这样的变量时..

var item = {name:John, items:[{name:Tony},{name:Jill}]};

并将其传递到指令中,如下所示

<tree item="item"></tree>

我得到一个嵌套的项目列表,但它们都说“约翰”。

我明白为什么会发生这种情况,因为第二个与第一个具有相同的范围..

我的问题是...我将如何在子元素中重复嵌入的内容,但范围指向子对象而不是顶部节点?

我已经阅读并尝试使用 $compile 和 transclude 函数,但我看不到任何方法来使其工作。

谢谢

最佳答案

它应该像你拥有的那样工作。我认为你只是混淆了 item 和 child。无法确定这一点,因为您的代码没有显示输出名称的位置。

在 ng-repeat 循环内,child 引用给定的 item.items,但 item 仍然与外部 item 相同。我提供了一个工作示例,其输出在评论中:

angular.module('myApp', [])
.directive('tree',[function($compile) {
return {
scope:{
item: "="
},
transclude:true,
template: "{{item.name}}" + // John, Tony, Jill
"<div class='tree-item'><ng-transclude></ng-transclude>" +
"<div id='tree-content' class='tree-content'>" +
"<div ng-repeat='child in item.items'>" +
"{{item.name}}" + // John, John
"{{child.name}}" + // Tony, Jill
"<tree item='child'><ng-transclude></ng-transclude></tree>" +
"</div>" +
"</div>",
link: function(scope,element,attrs) {}
}
}]
)
.controller('treeCtrl', ['$scope', function($scope) {
$scope.item = {
name: 'John',
items: [
{name: 'Tony'},
{name: 'Jill'}
]
};
}])

关于javascript - 在 Angular Directive(指令)中重复嵌入的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40095402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com