2

我对 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 附加到模板中,并且选定的元素子主题成为它的元素。如果只有一层,则模板上只有一个选择菜单。告诉我如何使用 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>

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

4

1 回答 1

2

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

<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);
            });
           });
    }
  };
}])
于 2013-11-14T08:36:28.423 回答