gpt4 book ai didi

javascript - 是否可以在其自己的模板中再次使用指令?

转载 作者:行者123 更新时间:2023-11-29 21:45:10 26 4
gpt4 key购买 nike

我正在尝试以 Angular 编写“评论”指令以加载嵌套评论(来自 Json 数据)并为子评论/回复重用相同的指令。

父评论本身加载得很好,但是当我尝试通过在其自己的模板中再次使用“评论”指令来显示子评论时,应用程序只是卡住,我不得​​不将其关闭。

下面是我的一些代码:

app.html: ---

  <ul ng-repeat="comment in View2.postItems | limitTo: 10">

<comments collection="comment"></comments>

</ul>

comments.html(指令):----

<li>      
<span>
{{ collection.data.commentText }}

<ul ng-show="{{collection.data.replies}}"
ng-repeat="comment in collection.data.replies.data.children">

<!-**child comments: this line causes the app to freeze:**-->
<comments collection="comment"></comments>

</ul>

</span>
</li>

评论.js:---

var comments = function(){
return {
templateUrl : 'modules/comments/comments.html',
restrict:'E',
scope:{
collection: '='
},
link: function(scope, element, attrs){

}
};
};

最佳答案

您可以使用 $compile 服务构建递归指令,以有条件地附加子指令。示例:( http://plnkr.co/edit/WpNp20DSjJhO412j3cSw?p=preview )

function comment($compile) {
return {
template: '<span ng-bind="comment.text"></span>',
link: function(scope, element) {
if (angular.isArray(scope.comment.collection)) {
element.append($compile('<comments collection="comment.collection"></comments>')(scope));
}
}
}
}

function comments(){
return {
template : '<ul><li ng-repeat="comment in collection"><comment></comment></li></ul>',
scope:{
collection: '='
}
};
}

关于javascript - 是否可以在其自己的模板中再次使用指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31469590/

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