使用 Angularjs 的递归和将 Elemnts 附加到 HTML 模板

Recursion using Angularjs and Append Elemnts to an HTML Template

本文关键字:HTML 模板 Elemnts Angularjs 递归 使用      更新时间:2023-09-26

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

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

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

我想要的 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>

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

您需要

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

<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 会创建新的范围(或用于创建,我目前正在使用有点过时的角度版本):

.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);
            });
           });
    }
  };
}])