角度递归模板

时间:2016-11-15 18:38:35

标签: angularjs templates angularjs-directive

我有一个带有项目模板的指令,该模板以递归方式引用自身,但没有正确地渲染超出第一级别的子项。我看了几个例子,似乎我的例子不同之处在于我的项目是通过AJAX请求按页面加载的。下面我链接到一个问题的例子。

http://plnkr.co/edit/16wf1MS7vbk3qH8tcE7q?p=preview

<div my-directive></div>

<script id="myDirectiveTemplate" type="text/ng-template">
    <h4>
        My directive
    </h4>
    <ul>
        <li ng-repeat="item in items" ng-include="'itemTemplate'"></li>
    </ul>
</script>

<script id="itemTemplate" type="text/ng-template">
    <p>
        {{ item.title }}
    </p>
    <ul ng-if="item.children.length">
        <li ng-repeat="child in item.children" ng-include="'itemTemplate'"></li>
    </ul>
</script>

我的指示:

angular.module("myApp")
.directive("myDirective", ["$timeout", function ($timeout) {
var scope;

function loadPage() {
    // makes an ajax call here to get a page
    scope.items.push({ title: "Item 1", children: [] });
    scope.items.push({ title: "Item 2", children: [] });
    scope.items.push({
        title: "Item 3",
        children: [
            {
                title: "Child 1",
                children: []
            },
            {
                title: "Child 2",
                children: []
            }
        ]
    });
}

return {
    restrict: "A",
    templateUrl: "myDirectiveTemplate",

    controller: ["$scope", function ($scope) {
        $scope.items = [];
        scope = $scope;
    }],

    link: function (scope, element, attrs) {
        $timeout(function () {
            loadPage();
        });
    }
};
}]);

1 个答案:

答案 0 :(得分:1)

我已经调整了逻辑位,这是您更新的SAMPLE

    <script id="myDirectiveTemplate" type="text/ng-template">
          <ul>
            <li ng-repeat="item in items">
              {{item.title}}
              <div ng-if="item.children.length > 0" ng-include="'itemTemplate'"></div>
            </li>
          </ul>
    </script>

   <script type="text/ng-template" id="itemTemplate">
    <ul>
      <li ng-repeat="item in item.children">
          {{item.title}}
         <div ng-if="item.children.length > 0" ng-include="'itemTemplate'"></div>
      </li>
    </ul>
  </script>

或者您可以尝试以下解决方案

<script id="myDirectiveTemplate1" type="text/ng-template">
  <ul>
    <li ng-repeat="item in items" ng-include="'itemTemplateUpdated'"></li>
  </ul>
</script>

<script type="text/ng-template" id="itemTemplateUpdated">
  {{item.title}}
  <ul ng-if="item.children.length > 0">
      <li ng-repeat="item in item.children" ng-include="'itemTemplateUpdated'">
      </li>
  </ul>
</script>