gpt4 book ai didi

javascript - 使用 Angularjs 递归并将元素附加到 HTML 模板

转载 作者:行者123 更新时间:2023-11-29 22:07:48 24 4
gpt4 key购买 nike

我对 Angularjs 很陌生。我正在开发一个应用程序,它使用 Angularjs 作为前端,使用 django-tastypie 作为后端。我正在做的是我有一个主题列表,其中主题作为多个级别的子 parent 相互嵌套。这些级别可以是多个。我的数据结构是

[{'id':1,
'name':'science',
'subtopics':[{
'id':1,
'name':'chemistry',
'subtopics':[{'id':1,
'name':'atom',
'subtopics':[{'id':1,'name':'science',:'subtopics':[]]
]]}}

我可能有多个级别的嵌套列表。我想做的是我想做的是,如果我从选择列表中选择一个具有子主题的元素,则 HTML 将附加到模板,并且所选元素的子主题成为其元素。如果只有一层,模板上将只有一个选择菜单。告诉我如何使用 Angular 在模板中表示这棵树。或告诉是否有人有更好的主意。

我想要的 HTML 渲染是这样的

<label>Topic Level 1:</label>
<select ng-model="qt_topic_level_1" ng-options="topic.name for topic in qt_topicslist_level_1" ng-change="showSecondLevelTopics()">
</select></br>
<label ng-show="secondleveltopicslabel" ng-true-value="true" ng-false-value="false">Topic Level 2:</label>
<select ng-model="qt_topic_level_2" ng-options="topic.name for topic in qt_topicslist_level_2" ng-change="getThirdleveltopics()" ng-show="secondleveltopicslist" ng-true-value="true" ng-false-value="false" >
</select></br>

表示如果子主题在所选主题列表中可用,则应将选择标签附加到模板以选择子主题等。第一次我只想显示根元素。然后单击要逐级显示子主题。

最佳答案

您需要将模板一分为二。第一个可以用作递归容器,即“主要”主题模板:

<div ng-repeat="topic in topics">
<div include-tpl="path/to/topic/tpl-recursive"></div>
</div>

以及单个主题的模板:

<div class="topic">
<!-- ..topic content.. -->

<div class="subtopics">
<div ng-repeat="topic in topic.subtopics">
<div include-tpl="path/to/topic/tpl-recursive"></div>
</div>
</div>
</div>

我使用自定义的 include-tpl 指令,因为 ngInclude 创建了新的范围(或用于创建,我目前使用的是有点过时的 angular 版本):

.directive('includeTpl', ['$compile', '$http', function($compile, $http){
return {
restrict: 'A',
link: function($scope, $element, $attrs) {
var replace = typeof $attrs.replace !== 'undefined';
$scope.$watch($attrs.includeTpl, function(value) {
if (!value) return;
$http.get(value).then(function(html){
var content = $compile(html)($scope);
if (replace) $element.replaceWith(content);
else $element.html(content);
});
});
}
};
}])

关于javascript - 使用 Angularjs 递归并将元素附加到 HTML 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19962518/

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